When you use new Date()
, you are constructing a Date
object using the current value of the system clock where the code is executing. The Date
object internally stores only a number of milliseconds since 1970-01-01T00:00:00Z (without consideration of leap seconds). In other words, Date
objects are always representing the UTC time.
However - there are many functions and parameters on the Date
object that work in local time. For example, when you call .toString()
on a Date
object, the computer's local time zone is applied to the internal UTC-based value, in order to generate a string that reflects local time.
In the case of console.log
- a standard object like Date
cannot be directly logged. Instead, most implementations will log a string value. How that value is created is entirely implementation specific, and not defined by the ECMAScript specification. Many implementations will return the same local-time based value that .toString()
returns. Some (FireFox, for example) will return the same UTC based value that .toISOString()
returns. It would be reasonable for an implementation to return the actual number of milliseconds stored (.valueOf()
), or some other representation. If you need consistency, don't just log the Date
object. Instead, log the output of one of its functions that returns a string or a number.
You also asked about subtracting two date objects. That will implicitly call .valueOf()
on each object, subtracting their UTC-based internal values and giving you the number of milliseconds between them. The most likely problem you are encountering is with how you construct the second Date
object. You didn't give an example of what timeStrFromDb
consists of, but understand that how that string is formatted directly relates to how the Date
object is constructed. If you aren't using a standardized format, or you aren't clear on whether the value is based on UTC or a specific offset from UTC, your string may be parsed differently than you expect.