Difference between moment.utc(date) and moment(date).utc() - javascript

Trying to understand the behaviour and difference between:
moment.utc(date) and moment(date).utc()
Using '2018-05-31' as a param:
moment.utc('2018-05-31').format() will give:
‌2018-05-31T00:00:00Z
while moment('2018-05-31').utc().format() will give:
2018-05-31T04:00:00Z
I am executing both in EST timezone.

The first moment.utc(String) parses your string as UTC, while the latter converts your moment instance to UTC mode.
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().
This brings us to an interesting feature of Moment.js. UTC mode.
See Local vs UTC vs Offset guide to learn more about UTC mode and local mode.
console.log( moment.utc('2018-05-31').format() );
console.log( moment('2018-05-31').utc().format() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

Related

How to convert "2017-07-27T08:02:17+0200" to local date-time and zone using moment.js

How to convert "2017-07-27T08:02:17+0200" to local date-time and zone using moment.js?
Here 08:02:17 is hour:minute:second and +0200 is time-zone. My local time-zone is GMT+6. I want to convert that date as my local date-time and zone. I've tried this so far:
moment.utc('2017-07-27T08:02:17+0200','YYYY-MM-DDThh:mm:ssZZ').local()
But it is returning Invalid Date by moment.js
As stated here
By default, moment parses and displays in local time.
Your input string includes UTC offset, so you can simply use moment(String, String).
Note that as stated here:
Moment's string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time.
so there is no need to use local().
var m = moment('2017-07-27T08:02:17+0200', 'YYYY-MM-DDTHH:mm:ssZZ')
console.log(m.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
For the local the moment itself will do, but, if you want a specific timezone, you can use the tz method with the location name (as defined in Moment Timezone):
moment.tz("2017-07-27T08:02:17+0200", "America/Toronto").format();

moment js, converting EST string to UTC

I'm a new developer and I have been stuck on this for a while, how would I convert the following date to it's UTC version (no utc prefix/suffix needed) in moment JS?
05/03/2016 16:00
I tried:
var b = "05/03/2016 16:00";
moment.utc(b).format();
"2016-05-03T16:00:00Z"
I would like the final result to be exactly as b, but its UTC equivalent. What am I missing?
You're missing the input format and the output format.
Without an input format, your date could be interpreted as either May 3rd, or March 5th, depending on the culture.
Without an output format, moment has no way to know what kind of string you want, so it defaults to the full ISO8601 extended format.
You're also missing the conversion. If the input is local time and you want UTC, then you should parse it with moment(...) then convert it to UTC with the .utc() function.
In summary:
moment(b, 'MM/DD/YYYY HH:mm').utc().format('MM/DD/YYYY HH:mm')
Also note that it's converting from the local time where the code is running. in your question you asked about EST. If your local time zone is something else, then EST will not apply to the above. You would instead need to use the moment-timezone add-on to do the following:
moment(b, 'MM/DD/YYYY HH:mm', 'America/New_York').utc().format('MM/DD/YYYY HH:mm')
moment(b).utc();
Will change it to a utc time, you might still need to add parameters to format() to make sure it displays the way you originally wrote it.
moment(b).utc().format("MM/DD/YYYY HH:mm");

convert time of certain timezone to UTC using momemtjs

I have a time in a specific timezone , I want to covert it to UTC . how can I achieve that using moment timezone ?
http://momentjs.com/timezone/
in the documentation this is how to convert :
jun.tz('America/Los_Angeles').format('ha z');
I am just not sure what timezone name to pass to convert it to UTC, or is there another function to use?
You can easily construct a moment in a specific time zone by using the moment.tz(...) syntax. This is slightly different from doing conversions with the .tz(...) function of an existing moment object, which is what you showed in your question.
var m = moment.tz('2016-03-25 08:00:00', 'America/Los_Angeles')
Once you have a moment object, you can convert it to UTC by calling the .utc() function. You can then format it however you like.
moment.tz('2016-03-25 12:34:56', 'America/Los_Angeles').utc().format()
// output: "2016-03-25T19:34:56+00:00"

new Date() vs Date() and why does it return a different time (-2 hours)?

I have these 2 console logs, but they return different times (-2 hours off).
console.log(new Date()) // Date 2015-04-20T15:37:23.000Z
console.log(Date()) // "Mon Apr 20 2015 17:37:23 GMT+0200 (CEST)"
I know using Data() is the same as using the constructor and calling .toString().
However, i do need the Date() time and not the new Date() time. So why is it returning the wrong time and how can i reset it to output the correct one?
thx,
So why is it returning the wrong time and how can i reset it to output the correct one?
Your first statement is calling console.log with a Date object. It appears that whatever browser/console plugin you're using chooses to display that Date object by using an ISO-8601 string in UTC. E.g., the format is chosen by the console implementation.
Your second statement is calling console.log with a string, so the format is chosen by the Date implementation. The specification makes no requirement on what that string format must be from JavaScript engine to JavaScript engine (yes, really*) other than that it must be in the local timezone.
Apparently, on your browser, the console implementation and the Date#toString implementation don't match up.
However, i do need the Date() time and not the new Date() time.
Those strings define the same moment in time (plus or minus a couple of microseconds); it's just that the strings have been prepared with different timezone settings.
If you need to log a string to the console in local time, use
console.log(String(new Date()));
...to reliably get the string from the Date object, not something generated by the console.
* Yup, the format you get from Date#toString is undefined and entirely up to the JavaScript implementation; the only requirement is that Date() and Date.parse() can both parse the string toString outputs and get back to the original date. (JavaScript didn't even have a standard date/time format until ES5, and it only applies to the toISOString method, not toString. And ES5 got it slightly wrong and it had to be amended in ES6, leading to the unfortunate situation at the moment where Chrome does one thing and Firefox does another when parsing strings in the new date/time format with no timezone on them.)
Those are the same time. The string generated by Date() just uses a different timezone, as can be seen from the GMT+0200 (CEST) suffix.
So if you need your time string in your local timezone, just use .toString() instead of .toUTCString().

Format date in a specific timezone

I'm using Moment.js to parse and format dates in my web app. As part of a JSON object, my backend server sends dates as a number of milliseconds from the UTC epoch (Unix offset).
Parsing dates in a specific timezone is easy -- just append the RFC 822 timezone identifier to the end of the string before parsing:
// response varies according to your timezone
const m1 = moment('3/11/2012 13:00').utc().format("MM/DD HH:mm")
// problem solved, always "03/11 17:00"
const m2 = moment('3/11/2012 13:00 -0400').utc().format("MM/DD HH:mm")
console.log({ m1, m2 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
But how do I format a date in a specifc timezone?
I want consistent results regardless of the browser's current time, but I don't want to display dates in UTC.
As pointed out in Manto's answer, .utcOffset() is the preferred method as of Moment 2.9.0. This function uses the real offset from UTC, not the reverse offset (e.g., -240 for New York during DST). Offset strings like "+0400" work the same as before:
// always "2013-05-23 00:55"
moment(1369266934311).utcOffset(60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).utcOffset('+0100').format('YYYY-MM-DD HH:mm')
The older .zone() as a setter was deprecated in Moment.js 2.9.0. It accepted a string containing a timezone identifier (e.g., "-0400" or "-04:00" for -4 hours) or a number representing minutes behind UTC (e.g., 240 for New York during DST).
// always "2013-05-23 00:55"
moment(1369266934311).zone(-60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).zone('+0100').format('YYYY-MM-DD HH:mm')
To work with named timezones instead of numeric offsets, include Moment Timezone and use .tz() instead:
// determines the correct offset for America/Phoenix at the given moment
// always "2013-05-22 16:55"
moment(1369266934311).tz('America/Phoenix').format('YYYY-MM-DD HH:mm')
A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:
moment.tz(date, format, timezone)
moment(date, format).tz(timezone)
Assuming that a timezone is not specified in the date passed in:
The first code takes in the date and assumes the timezone is the one passed in.
The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.
Example:
moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"
moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"
My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.
In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"
NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors
Assuming the timezone is specified in the date passed in:
In this case they both behave equally
Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.
Use moment-timezone
moment(date).tz('Europe/Berlin').format(format)
Before being able to access a particular timezone, you will need to load it like so (or using alternative methods described here)
moment.tz.add('Europe/Berlin|CET CEST CEMT|-10 -20 -30')
.zone() has been deprecated, and you should use utcOffset instead:
// for a timezone that is +7 UTC hours
moment(1369266934311).utcOffset(420).format('YYYY-MM-DD HH:mm')
I was having the same issue with Moment.js. I've installed moment-timezone, but the issue wasn't resolved. Then, I did just what here it's exposed, set the timezone and it works like a charm:
moment(new Date({your_date})).zone("+08:00")
Thanks a lot!
Just came acreoss this, and since I had the same issue, I'd just post the results I came up with
when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.
moment(moment.utc('1.1.2014').format());
Well, came in handy for me to support across timezones
B
If you pass the timestamp as the parameter to moment() (e.g if the timezone is Asia/Hong_kong which is +08:00), what I do is:
const localDateTime = moment((item.createdAt.seconds + 8 * 3600) * 1000).format('YYYY-MM-DD HH:mm:ss');
You can Try this ,
Here you can get the date based on the Client Timezone (Browser).
moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')
The regex basically gets you the offset value.
Cheers!!

Categories