How to convert GMT to Local Time using moment in JavaScript? - javascript

I'm trying to convert a time in the format of '2019-07-15T08:57:58.749081' to a local time using the format of 'Month Day(th/st) Year Hour:mm am/pm". So anything like "September 9th 2018 9:40 pm" or "July 18th 2019 9:40 pm", etc.
This is to use the moment package imported into a ReactJS app. I can get the format to look right but the time is still GMT/UTC. To do this format I used
var dateTime = moment(param).format('MMMM Do YYYY h:mm a');
But I really need the formatted time in my own local time.

Since the input string is in ISO 8601 format, and the time basis is UTC, the string should contain a trailing Z. In other words, it should look like 2019-07-15T08:57:58.749081Z. Since it doesn't, you have two choices.
You can append the Z yourself:
moment(param + 'Z').format('MMMM Do YYYY h:mm a')
You can parse as UTC and then switch to local mode before formatting:
moment.utc(param).local().format('MMMM Do YYYY h:mm a')

Related

regex to verify GMT&Chinese date time format

I want to validate the date- time format which is like 'Wed Oct 25 2017 12:59:00 GMT+0800 (中国标准时间)' for this i am looking for a regex.
Tried few combinations but those did not work for me.
I would suggest using moment.js instead to parse and validate your datetime string:
var time = 'Wed Oct 25 2017 12:59:00 GMT+0800 (中国标准时间)';
console.log(moment(time, 'ddd, MMM DD YYYY HH:mm:ss ZZ').isValid());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
The format string 'ddd, MMM DD YYYY HH:mm:ss ZZ' tells Moment how to read your GMT+0800 (China Standard Time) input string.
Note: All date objects created with Moment, no matter, the time zone will default to the current time zone, unless specified directly, e.g. .zone("+08:00") To get UTC times back, use moment.utc() instead. For more information on time zones, check out the section Moment Time Zones.
Further reading: Moment.js: A Better Date Library for JavaScript

How to convert a given date/time for a specific timezone (not local) to UTC using moment.js and moment-timezone.js

How can I I want to convert a given date/time for a specific timezone (not local) to UTC using moment.js and moment-timezone.js
I use:
var s = moment("10/15/2014 09:25 AM").tz("America/Los_Angeles").format('hh:mm:ss a');
I have a difficulty when I want to give a value on moment().
Let me explain you the facts:
I have to take a date/time value from a cell with the following format:10/15/2014 09:25 AM (MM/DD/YYYY h:mm a). This value is not a constant one, its the opened time for some entries.
I want to transform this string in UTC. Unfortunately, the string is not my local time, is in America/Los_Angeles (PDT/PST) timezone. I want also to take care automatically about PDT(9 Mar, 2 Nov) and PST.
-10/15/2014 09:25 AM America/Los_Angeles -07:00 => 10/15/2014 04:25 PM UTC 00:00
-12/15/2014 09:25 AM America/Los_Angeles -08:00 => 12/15/2014 05:25 PM UTC 00:00
How can I do this?
If I use: Var s = moment("10/15/2014 09:37 PM").tz("America/Los_Angeles").format('hh:mm:ss a');
...it will be parsed as my local time and it will be converted to America/Los_Angeles.
- 10/15/2014 09:25 AM Eastern European Time +03:00 => 10/15/2014 11:25 PM America/Los_Angeles +07:00
I think that a short description for my problem is this:
- How can I "tell" to script that this string 10/15/2014 09:37 AM is from a specific timezone. After this, the conversion to UTC is piece of cake.
Thanks.
You must provide a pattern when you want to parse a date string with a specific timezone, except for UTC. For UTC you can just provide the date string.
Usage: moment.tz(string, pattern, zoneString)
In your case:
var moment = require("moment-timezone");
var d1 = moment.tz("10/15/2014 09:25 AM", "MM/DD//YYYY hh:mm A", "America/Los_Angeles");
d1.toString(); // Wed Oct 15 2014 09:25:00 GMT-0700
d1.tz("UTC").format('hh:mm:ss a'); // '04:25:00 pm'
If you omit the formatter the parsing is wrong, but there is a deprecated note: https://github.com/moment/moment/issues/1407
Read this http://momentjs.com/timezone/docs/#/using-timezones/parsing-ambiguous-inputs/ to handle DST

Any way to parse a time string using Moment.js but ignore timezone info?

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400

Trying to implement momentjs to display localtime

Before asking this question I have searched all stackoverflow and read the docs but I can't just understand how to convert one UTC date to local time of an user and display it in his format. I keep trying different methods but I keep getting the same time again and again.
so my django returns obj.created_on in UTC as - 2013-12-26T13:52:24 - no timezone Info here but I know its UTC
Now I want momentjs to auto detect the user's timezone and convert it in that timezone.
Can I have proper syntax for the same?
I was trying this as well:
new_date = moment(obj.created_on).utc().local().format()
Moment has two different utc functions:
One is on a moment instance, used to switch the mode to UTC.
moment(input).utc()
The other is on the moment prototype, used to interpret the input as already in UTC.
moment.utc(input)
So, you want this syntax:
moment.utc(obj.created_on).local().format()
moment($('#start').val()).utc().format("ddd, DD MMMM YYYY H:mm:ss");
moment($('#end').val()).utc().format("ddd, DD MMMM YYYY H:mm:ss");
will display Date format in UTC if you want the date in local format.
moment($('#start').val()).utc().local().format("ddd, DD MMMM YYYY H:mm:ss");
moment($('#end').val()).utc().local().format("ddd, DD MMMM YYYY H:mm:ss");
Default will take as GMT time. We need to convert that into our local format.

How to create time in a specific time zone with moment.js

I have this backend that sends me a pre formatted time in a set time zone, but without any information for the said time zone. The strings are like: "2013-08-26 16:55:00".
I can create a new moment.js instance with this string:
var time = moment("2013-08-26 16:55:00") //this creates time in my tz
but this will only create an instance in my own time zone.
Moment.js have a plugin that can create instances of the object in specific time zones and it works great, but I can't say what time I want the object to point to.
If I'm in New York and I do this:
var time = moment("2013-08-26 16:55:00").tz("America/Los_Angeles");
the resulting time will be 13:55 instead of 16:55 but in LA.
What I want is to create an instance that will say 16:55, but in LA time.
The reason I'm asking is because I want to do this:
var now = moment.tz("America/Los_Angeles");
var end = moment("2013-08-26 16:55:00"); //plus something to convert LA time
var timeLeft = end.diff(now, "minutes");
Is there a way to do that?
In most cases, you can simply do this:
moment.tz("2013-08-26 16:55:00", "America/Los_Angeles")
If you require input other than ISO8601, then specify the format string as the second parameter, and the time zone as the third:
moment.tz("8/26/2013 4:55 pm", "M/D/YYYY h:mm a", "America/Los_Angeles")
And if you need to use moment's "strict parsing" mode, then that goes in the third parameter, and the time zone moves to the fourth position:
moment.tz("8/26/2013 4:55 pm", "M/D/YYYY h:mm a", true, "America/Los_Angeles")
If you want to calculate everything in a specific timezone you want to set the default time zone using
A) moment.tz.setDefault("America/Los_Angeles");
For my use case (in a node.js project) I just set it right after requiring the moment modules like so:
let moment = require('moment');
require('moment-timezone');
moment.tz.setDefault("America/Los_Angeles");
All calls to moment() thereafter will create the time in the "America/Los_Angeles" setting, which is NOT the same as using:
B) moment.tz("2017-03-04 00:00", "America/Los_Angeles")
OR
C) moment("2017-03-04 00:00").tz("America/Los_Angeles")
both of which would create the moment object in UTC time (unless you already changed the default), and then convert it to be the Los Angeles timezone.
Running B or C above in the browser console yields:
_d: Fri Mar 03 2017 16:00:00 GMT-0800 (PST)
_i: "2017-3-4 00:00"
Notice _d shows March 3 4:00pm; this is because the moment object is created with March 4 12:00am in UTC time, then converted to Pacific timezone, which is 8 hours behind/the previous day.
source: http://momentjs.com/timezone/docs/#/using-timezones/default-timezone/
install moment-timezone
> npm install moment-timezone
Or see https://momentjs.com/timezone/docs/
.tz(string, string)
moment.tz("2020-01-02 13:33:37", "Iran/Tehran")
Just to make something abundantly clear, that is implied in other answers but not really stated:
You absolutely must either
use ISO8601 as your date format or
specify the format your string is in
.. when using the .tz(string datetime, [string format,] string zone) function, if you want moment to interpret the datetime argument you give to be in the zone you give. If you omit format, be sure to pass an ISO8601 formatted string
For 2 days I went round in circles, because my API was delivering a time string like "03 Feb 2021 15:00" and sure, it parsed OK, but it always used the timezone from my local machine, then converted to the timezone I gave:
//this always resulted in "2021-02-03 10:00 EST" if run on a machine in UTC
moment.tz("03 Feb 2021 15:00", "America/Indianapolis").format("YYYY-MM-DD HH:mm z")
This was massively confusing: the parsing was clearly working fine, because the date was right but the time was always wrong by however many hours there were between the machine and the given zone string
Switching to ISO format input worked:
//this always resulted in "2021-02-03 15:00 EST" if run on a machine in UTC
moment.tz("2021-02-03 15:00", "America/Indianapolis").format("YYYY-MM-DD HH:mm z")
As did declaring:
//this always resulted in "2021-02-03 15:00 EST" if run on a machine in UTC
moment.tz("03 Feb 2021 15:00", "DD MMM YYYY HH:mm", "America/Indianapolis").format("YYYY-MM-DD HH:mm z")
I hope this saves someone some time
I had a similar issue for which i had to use New York based time so i had to consider for daylight savings. I tried using the above few answers but wasn't able to get it working. Then I solved my issue like the below code
import moment from 'moment-timezone'
const time = timestamp
const offset = moment.tz.zone('America/New_York')?.parse(time)
const date = moment(time).add(offset, 'minutes').toISOString()
or you can do this way which will consider the time offset on its own when you display locally.
const time = moment.tz(timestamp, 'America/New_York')
const localtz = moment.tz.guess()
const date = time.clone().tz(localtz)
this gives you an ISO string which you can use as below
moment(date).local().format('dddd, MMM DD YYYY, hh:mm A')
or in whatever format you would like to display it

Categories