0

I want a date-time object in UTC time, and not a UTC date-time string.

The following code helps me to get the UTC time as a string:

moment.parseZone(new Date()).utc().format()

The output of the code above is:

"2019-01-14T12:43:23Z"

The above is a string, which I do not want. What I want is a date-time object. This is how I convert a date-time string to a date-time object:

new Date(moment.parseZone(new Date()).utc().format())

Unfortunately the above code coverts the output into local time AGAIN, an example of which is shown below:

Mon Jan 14 2019 18:10:54 GMT+0530 (India Standard Time)

How do we stop a UTC date-time object from converting to local date-time?

Edit-01: How do I perform calculations using a date-time object in UTC time?

Edit-02: Functional Explanation:

There are people with different time zones. We know the UTC time difference. I want to build a table of each persons’ time in their local time.

Example: My timezone is +5:30 UTC (my time is currently 01/14/2019 9:00pm) and a person from San Francisco has a timezone of -8:00 UTC (his/her time is currently 01/14/2019 7:30am).

At present, what I am trying to do is add the time difference (-8:00 UTC) to UTC time to find San Francisco person’s local time. This does not work because when I convert the UTC date-time string to a date object it will convert into local time.

  • 1
    I understand it might just be a proof of concept for the question but please be aware that feeding Moment.js with the result of prior Vanilla JavaScript date manipulations kind of beats the purpose of using the library in the first place because you're no longer sure of what your starting data actually are. – Álvaro González Jan 14 '19 at 13:19
  • You are correct that it is impractical to use Vanilla JS with Moment.JS... I was hoping/wondering if there was a way to do this using moment, which is why I added the tag. – Suren Dias Jan 14 '19 at 13:31
  • ECMAScript Dates **are** UTC, always. You don't have to do anything. Just use UTC methods (such as *getUTCHours*, *setUTCHours*) for all your calculations if you want to ignore timezones and daylight saving. The non–UTC methods take account of daylight saving and system timezone settings. Just don't use them. – RobG Jan 14 '19 at 22:15

1 Answers1

4

Javascript dates have no timezone! It's the 'static' methods that you use for serializing that sneakily apply one. The output that's worrying you is the standard output of Date.toString(), used in the console. The underlying date is likely fine (you just created it from nothing, so there are no possible deserialization issues). You just need to specify a UTC method when you serialize. Try Date.toISOString(), or Date.toLocaleDateString({},{timeZone:'UTC'})

edit after functional explanation...

Ok here are a few things you can do. Kennedy was assasinated at 12:30pm, the 22nd of November 1963 Central Standard Time

// create a date object to represent this moment...
const byeByeKennedy = new Date("1963-11-22T12:30:00-06:00");

// this is a date object, representing a moment. We used a
// timezone for it's creation, but now it has no notion of timezone.

// if you want to know what time it was IN THE TIMEZONE OF THE USER, 
// just do toString(), or leave timezone blank. Formatting in the 
// timezone of the user is always the default in javascript.
// This does not mean that the Date intrinsically has a timezone though!
console.log('My local time when kennedy was killed... ' 
+ byeByeKennedy.toString());

// If we want to format this date with it's "original" timezone, we need
// to store the timezone separately, then use it again to serialize...
console.log('Local time in Dallas when Kennedy was killed... ' 
+ byeByeKennedy.toLocaleString({},{timeZone:"America/Chicago"}))

// If you, sitting in India, need to know what time it was for 
// your user in San Francisco when kennedy
// was killed, you need to supply the timezone of San Francisco...
console.log('Local time in San Francisco when Kennedy was killed... ' 
+ byeByeKennedy.toLocaleString({},{timeZone:"America/Los_Angeles"}))

// If you want to serialize this date, for example to send it to a server, use ISO...
console.log('Use ISO for serializing/sending... ' 
+ byeByeKennedy.toISOString());

// OR IF YOU JUST WANT TO KNOW WHAT TIME IT IS IN SAN FRANCISCO...
console.log('SAN FRANCISCO TIME NOW... '
+ new Date().toLocaleString({},{timeZone:"America/Los_Angeles"}))

You can, if you absolutely have to, directly add the timezone offset to a Date, then format it specifying UTC, but this is a terrible idea because you will need to manage daylight saving and other subtleties. Please don't do this. It's much better to be really clear about timezone at the moment your create, then whenever you format.

Community
  • 1
  • 1
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
  • Thank you for the quick response. I used your methods above. The output of 'new Date().toISOString()' is correct. But, the output is still a string. What I want is a date-time object to perform addition and subtraction calculations. When I converted the output of above using 'new Date(new Date().toISOString())' the output was once again local time, which is not what I want. Again what I want is something like this 2019-01-14T13:29:42.326Z but not "2019-01-14T13:29:42.326Z" – Suren Dias Jan 14 '19 at 13:30
  • The output has to be a string, otherwise it would be invisible ! new Date() gives you what you want (a Date object initialized to the present moment). The entire contents of your Date object can be seen using myDate.getTime(). It's just a number, indicating a moment in time. *It has no timezone*. (The timezone is applied when converting to a string for display in the console.) Start doing your arithmetic, and see if the results are what you expect. Just be clear that a some point you need to serialize, and at that point you wil have to choose a timezone. – bbsimonbb Jan 14 '19 at 13:42
  • I understand that ‘myDate.getTime()’ will yield a number that represents this moment in time and that I can run calculations on it. However, the problem is what we need is not the current time, it is the UTC time. In other words, I need to perform calculations in UTC time. – Suren Dias Jan 14 '19 at 14:41
  • I'm running out of different ways to tell you that ***javascript dates have no notion of timezone***. Your sentence "I need to perform calculations in UTC time" **makes no sense**. You perform calculations on a number. UTC is a timezone, and a timezone is only relevant when you're creating Date objects or converting them back to strings for display. Can you tell us what you're really trying to do, in functional terms. It will likely help to work with a real example. – bbsimonbb Jan 14 '19 at 15:12
  • Got it. Functional Explanation: There are people with different time zones. We know the UTC time difference. I want to build a table of each persons’ time in their local time. Example: My timezone is +5:30 UTC (my time is currently 01/14/2019 9:00pm) and a person from SF has a timezone of -8:00 UTC (his/her time is currently 01/14/2019 7:30am). At present, what I am trying to do is add the time difference (-8:00 UTC) to UTC time to find SF person’s local time. This does not work because when I convert the UTC date-time string to a date object it will convert into local time. – Suren Dias Jan 14 '19 at 15:36
  • @SurenDias If you're planning to store UTC offsets (UTC+05:30) somewhere just remember that in many parts of the world they change twice a year. – Álvaro González Jan 14 '19 at 17:32
  • @bbsimonbb— "*I need to perform calculations in UTC time*" makes complete sense, the OP should just use UTC methods exclusively (as you've already advised). UTC isn't a timezone, it's a standard. It's more–or–less aligned with GMT, which is a timezone. – RobG Jan 14 '19 at 22:19
  • @SurenDias—there are also historic timezone changes pretty much everywhere except GMT, particularly around 1900 but continuing to current times. – RobG Jan 14 '19 at 22:22
  • @robg you know this stuff better than me. I want to insist on the difference between creating and formatting dates on the one hand, and calculations on the other. For creating and formatting, timezone is vital. For calculations, not so much. You can add and subtract on dates without knowing or caring about their timezone. There are duration functions that care about day/month/year boundaries crossed, which are timezone dependent, but that's getting pretty exotic. – bbsimonbb Jan 14 '19 at 22:30
  • @bbsimonbb— "*You can add and subtract on dates without knowing or caring about their timezone*" isn't true in a general case. Whether timezones are considered is based on business logic, same for different number of days in month when adding months, and whether 29 Feb + 1 year is 28 Feb or 1 Mar is also dependent on business rules (generally government administrative rules). – RobG Jan 14 '19 at 23:06
  • This stuff might be considered "edge cases", but they're the ones that fail weirdly in difficult to find circumstances. – RobG Jan 14 '19 at 23:07