5

I want to get utc date using moment or any other possibilities. utcString = moment.utc(someDate)).format() is giving utc string not utc date. I am not able to perform operations like utcString.getDate() , etc using this. Please help me in providing with utc date object.

moment.utc(new Date()).toDate() is converting date again to my local time.

for example: I want the string of utc format like "2019-10-31T00:00:00.000Z" to get converted to utc date and perform operations(like getDate(), getFullYear(), etc) which could be performed using Date() object

qaz2625 qaz
  • 103
  • 2
  • 2
  • 10
  • No. I want utc time not local time. Please go through my question – qaz2625 qaz Sep 05 '19 at 18:15
  • then you could use `moment().utc().format('DD/MM/Y hh:mm:ss A')`. You can get value in any format `date`, `month`,`year` etc. Check the documents [utc()](https://momentjs.com/docs/#/parsing/utc/) – Narendra Jadhav Sep 05 '19 at 18:17
  • Format method return string. Not date object – qaz2625 qaz Sep 05 '19 at 18:29
  • but this `moment().utc()` is again date. you can check – Narendra Jadhav Sep 05 '19 at 18:31
  • moment().utc().getTime(). Will not work. Please check – qaz2625 qaz Sep 05 '19 at 18:32
  • @NarendraJadhav - this question appears to be related to react-date-picker, based on https://stackoverflow.com/questions/57810435/get-utc-date-not-utc-string-in-javascript/57810939#comment102053565_57810768 – ecc521 Sep 05 '19 at 18:34
  • Given the number of answers, it is probably impossible to save, and should be closed. – ecc521 Sep 05 '19 at 18:35
  • @qaz2625qaz first think, if you are using `momentjs` then please read the documents . In moment don't have method `.getTime()`. If we want to get time using moment then we need to use `moment().valueOf()`. – Narendra Jadhav Sep 05 '19 at 18:39
  • please provide me solution (irrespective of momentjs) to get utc date object. I mean strings like ```"2019-10-31T00:00:00.000Z"``` to date object – qaz2625 qaz Sep 05 '19 at 18:43
  • moment().valueOf() returns number not date object – qaz2625 qaz Sep 05 '19 at 18:47
  • Does this answer your question? [How do you convert a JavaScript date to UTC?](https://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc) – Michael Freidgeim Jan 09 '22 at 04:05

7 Answers7

14

From the MDN Documentation on the Date object:

Creates a JavaScript Date instance that represents a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

In other words, the Date object is simply an abstraction that contains a single value, and that value always in terms of UTC. If you want to see that value, call either .valueOf() or .getTime(), or coerce it to a Number (ex: +d).

There are many features of the Date object that can expose that value in different ways, such as in a standardized string format, a human readable string format, or various other numbers that represent partial component values (ie. year, month, day, hour, minute, second, millisecond). Some of these functions use UTC when determining their output (such as .toISOString(), .getUTCFullYear(), etc.), and others use the computer's local time zone when determining their output (such as .toString(), .getFullYear(), etc.).

It's easy to get confused by this, especially if calling console.log directly on a Date object. The thing to remember there is that the console logging functionality is implementation specific. You may see a human readable string that looks like local time as if you called .toString(), but some implementations give you a string that looks like UTC time in ISO format as if you called .toISOString(). Really, the implementation can do whatever it wants when it comes to logging. It could print out a hissing cat.

To add to the confusion, the Date constructor takes its numeric parameters in terms of local time, so one might think new Date(2019,8,5,0,0,0) was a Date object in local time, but actually it's converting to UTC during construction and recording the corresponding timestamp. One can pass new Date(Date.UTC(2019,8,5,0,0,0)) to have those values interpreted as UTC, but the Date object itself is in UTC either way.

The key point is, don't think that because you see local time that the Date object is in local time. It isn't. It never is. Thus, asking for it in a different time zone is also not possible. Asking for it in UTC is what you already have.

I want the string of utc format like "2019-10-31T00:00:00.000Z" to get converted to utc date and perform operations(like getDate(), getFullYear(), etc)

You wouldn't call getDate or getFullYear. Those functions internally ask for the computers's local time zone and apply it to the timestamp before determining their result. Instead you would call for getUTCDate or getUTCFullYear, which do not apply the local time zone.

... Actually I am using react-date-picker. ... (from your comments)

There are lots of date pickers out there. If you don't get the functionality out of the one you're using, try another.

The best ones will do one of two things when it comes to time zones:

  • They might offer a setting for the "mode" of the picker, typically either local or UTC, or perhaps a specific UTC offset or time zone ID. This would allow you to pre-determine how you want the picker to behave with regard to its inputs and outputs.

  • They might simply provide the input and output as a String, rather than as a Date object. This would allow the picker to behave in a neutral way, and you would then interpret the user's selection in whichever manner you pleased. (BTW, HTML5's <input type="date"> works this way.)

Unfortunately, there are lots of date pickers that don't work that way and assume you simply want a Date object that is created based on local time. To contend with that, you will need to lie a little bit.

For example, say I pick 2019-09-05 from a date picker that assumes my local time zone. It does internally new Date(2019, 8, 5), or perhaps it does new Date("2019-09-05T00:00:00.000"). Either form would be interpreted as local time before the the Date object records the corresponding timestamp value. But I didn't actually want that - I wanted the user to pick a UTC date. So I add this bit of code to adjust the object (d) returned from the picker:

d.setTime(d.getTime() - (d.getTimezoneOffset() * 60 * 1000));

This technique is called epoch shifting, as it shifts the basis of the timestamp away from (or towards) the 1970-01-01T00:00:00.000Z Unix epoch. In this case, it's the original Date object (the one created by the picker) that was created incorrectly, and thus the above shifts it back to the standard Unix epoch.

Keep in mind that this technique is all about having your user pick a UTC-based value, and get it back to a regular Date object. It is not to be used to have your user pick a local-value and convert it to UTC. For that you must used the functions designed for that purpose (getUTCFullYear, getISOString, etc.).

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Does you suggestion to use epoch shifting contradicts to your comment “ This answer demonstrates another common implementation of "epoch shifting" which is dangerous in isolation, as it can fail near edge cases like DST transitions. Not recommended. – Matt Johnson-Pint [Jun 20 '16 at 23:58](https://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc#comment63317490_11964609) ? – Michael Freidgeim Jan 09 '22 at 03:35
  • 1
    @MichaelFreidgeim - Epoch shifting is a technique. It's usually abused, so often not recommended. It is ok as long as the shifted `Date` object is not exposed or returned. For example, Moment.js uses it - but only internally. In the case of this question, epoch shifting is being used to counteract the effects of a `Date` object being created based on the local time zone when it actually was intended to be based on UTC. So, shift to reflect the intent. Think of it as a hack of a workaround. It would have been much better if the picker created the `Date` object in terms of UTC to begin with. – Matt Johnson-Pint Jan 10 '22 at 01:03
2

The JavaScript date object has functions for getting the UTC date, year, string, etc. You can find all of the different functions here. Example:

let date = new Date();
console.log("UTC Date: " + date.getUTCDate());
console.log("UTC Year: " + date.getUTCFullYear());
console.log("UTC Hour: " + date.getUTCHours());
console.log("Full String: " + date.toUTCString());
Jesse
  • 1,386
  • 3
  • 9
  • 23
  • Actually Iam using react-date-picker. In which disabled property is used to indicate all disabled dates. For example disabled=new Date(). In react-date-picker package it is performing getTime() operation. So I can't modify its functionality to use getUTCTime(). Instead of that I want to pass utc date itself to that property. For example disabled=utcdate – qaz2625 qaz Sep 05 '19 at 18:24
  • Well then I believe that would be a setting within the plugin, as the `getTime()` function returns the time in epoch format, meaning somewhere in the plugin it would have to convert epoch time to the local time zone. – Jesse Sep 05 '19 at 18:29
0

let d = moment();
let d_utc = moment.utc();
let full_year = d_utc.format('YYYY');
let month = d_utc.format('MM')
console.log(d);
console.log(d_utc);
console.log(d.format());
console.log(d_utc.format());
console.log(full_year);
console.log(month);
<script src="https://momentjs.com/downloads/moment.js"></script>

You can format the date as you wish (local time or UTC) and put the result into variables.

0

You can avoid using extra libraries by doing this fun thing:

var fooDate = new Date();
var utcDay = fooDate.getUTCDate();
fooDate.setDate(utcDay);

This will let you get the UTC date and update your already existing Date object with it.

EDIT: I'd recommend you checking Jesse's answer too, in case you need the whole thing in UTC format.

0

To convert "2019-10-31T00:00:00.000Z" to a Date object, you can try using new Date(). From there, you will be able to call methods such as getFullYear or getUTCString:

new Date("2019-10-31T00:00:00.000Z").getFullYear()

If you would like to use moment.js, you can get a native date using moment.toDate(). You can then call getFullYear(), etc, on the native date.

let time = moment.utc(new Date("2019-10-31T00:00:00.000Z"))
let UTCDate = time.toDate().getFullYear()

If you want a Date representing the current time, just call new Date()

ecc521
  • 576
  • 6
  • 14
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/199040/discussion-on-answer-by-ecc521-get-utc-date-not-utc-string-in-javascript). – Samuel Liew Sep 05 '19 at 23:05
-1

You can use JS Date class.

Create a Date instance : let date = new Date();

Then you can perform a lot of functionality on that date object. For example,

let d= new Date();
d.getDate()
//5
Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35
-1

I did not used any external library, in my case I have a hardcode text "UTC":

(i.e We will delete your account at ${tomorrowUtc} UTC)

So this is what I did:

const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();

const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);

// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.

This is kinda "hacky" as this is still using your local timezone, but if your goal is same as mine (to just display it with a hard coded timezone) then this would work.

I am L
  • 4,288
  • 6
  • 32
  • 49