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
Related
I got timestamp utc of new york from weather api, want to display current time in New York but it gives output something like this 'UTC Sun Dec 01 2019 05:00:00 GMT+0530 (India Standard Time)'.
See the code for reference
// Code 1
//I get timestamp_utc when console.log(data)
//timestamp_utc: "2019-12-01T05:00:00"
const utc = new Date(data.timestamp_utc)
console.log('UTC', utc)
// UTC Sun Dec 01 2019 05:00:00 GMT+0530 (India Standard Time)
// Code 2
// Another code for getting current time but, failed
var usaTime = new Date().toLocaleString("en-US", {timeZone: timezone}); // Here timezone is from props
console.log('USA time: '+usaTime) // USA time: 12/1/2019, 4:59:58 AM
I also have timezone data getting from weather API. My aim is to get current time based on timezone or utc timestamp. As you can see both my trials are unsuccessful. Expected output is 6:39 PM which is now current time in New York. Is there any good solution?
Let me start with your 'code 2'. This is the same as what you wrote but with the timezone filled in...
const timezone = "America/New_York";
const usaTime = new Date().toLocaleString( "en-US", { timeZone: timezone});
console.log( 'usaTime =', usaTime );
For me this works. I get the current time in NY formatted correctly for USA. I'm not sure why yours did not work but I wonder what you specified for the timezone string.
I also a bit puzzled by your 'Code 1'. The 'new Date()' that you created is being converted to a string and then printed by your console.log statement, but this should result in a ISO 8601 string and you seem to be getting a locale string (the date format).
Though the example string you gave is in ISO 8601 format, it is not explicitly UTC because it does not end with a Z, nor does it end with a time zone offset such as +00:00. Thus when you parse it with the Date constructor, it is interpreted as local time. You can fix this by adding the Z yourself (assuming the timestamp_utc field is consistently a string in that format):
// timestamp_utc: "2019-12-01T05:00:00"
const utc = new Date(data.timestamp_utc + 'Z'); // adding the Z forces parsing as UTC
Now you have a Date object. However, if you just pass it to console.log, the output you see is implementation dependent. You will either see the local time in the same format you'd get by calling toString, or you will see the UTC time in the same format you'd get by calling toISOString.
To get the time in a different time zone, now you can call toLocaleString and pass the timeZone option. This assumes that the time zone is a valid IANA time zone identifier, and that the environment where the code is running fully supports the time zone features of the ECMAScript Internationalization Specification (ECMA-402). This is indeed the case with most modern browsers, but you will not get correct output in older browsers such as Internet Explorer.
const usEasternTime = utc.toLocaleString("en-US", {timeZone: 'America/New_York'});
Lastly from your variable name usaTime, I think perhaps you might be under the assumption that the US has a single time zone, but it does not. You will need to pass the correct time zone identifier. See the list on Wikipedia.
Define the time zones of origin ($ sourceDate) and destination (to convert).
$sourceTimeZone = 'utc';
$targetTimeZone = 'America/Bogota';
Separate the components of the date of origin that is in the format ‘m / d / y h: m: s’.
list($month, $day, $year, $hours, $minutes, $seconds) = sscanf($sourceDate, "%d/%d/%d %d:%d:%f");
Build the DateTime object indicating the date and time zone in which it is located.
$datetime = new DateTime("{$year}-{$month}-{$day} {$hours}:{$minutes}:{$seconds}",
new DateTimeZone($sourceTimeZone));
Modify the time zone of the DateTime to the destination time zone.
$datetime -> setTimezone(new DateTimeZone($targetTimeZone));
Get the components of the new date with the modified time zone.
list($month2, $day2, $year2, $hours2, $minutes2, $seconds2) = sscanf($datetime -> format(‘m/d/Y H:i:s’), “%d/%d/%d %d:%d:%f”);
Show the dates.
echo "En {$sourceTimeZone}: {$day}/{$month}/{$year} {$hours}:{$minutes}:{$seconds}<br/>";
echo "En {$targetTimeZone}: {$day2}/{$month2}/{$year2} {$hours2}:{$minutes2}:{$seconds2}<br/>";
PD: For JavaScript this can help you Convert time to different timezone with jQuery
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
I have a requirement to convert a UTC time local time based on user timezone
I have two parameters utc time and users timezone as a string
ie
0,1,2,3 ...12 (timezone)
0,-1,-2,-3 ...-12 (timezone)
var utc = "2014-10-18T06:14:41.512Z"
tz = 5.5(Indian Standard Time)
Expected result Sat Oct 18 2014 11:44:28 GMT+0530
I have tried moment js
moment("2014-10-18T06:14:41.512Z").zone('+05:30').format('YYYY-MM-DD HH:mm')
and the result is correct.
But when i change the timezone to other it is not showing as expected result
tried
moment("2014-10-18T06:14:41.512Z").zone('+12:00').format('YYYY-MM-DD HH:mm')
result "2014-10-18 18:14" Expected 2014-10-18 19:18
12 is NewZeland timezone. Please help me to solve this issue. Thank you
Check this
var date = new Date('2014-10-19 17:00:34 UTC');
date.toString();
var timezone = "America/New_York";
var utcDate = "2014-10-19T10:31:59.0537721Z";
var localDate = moment.utc(utcDate).tz(timezone).format()
Also check
http://www.digitoffee.com/programming/get-local-time-utc-using-moment-js/94/
To adhere to international standards, you need to format your UTC date to include the time delimiter T, and the zone designator Z.
Z is the timezone designator for the zero UTC offset aka Zulu time.
You can read more about the International Date Standard ISO8601 format specifics here.
Once you've conformed to the international standard, the cross browser friendly approach is simple:
new Date('2014-10-19T17:00:34Z');
// Sun Oct 19 2014 12:00:34 GMT-0500 (Central Daylight Time)
A time zone is not an offset. An offset is only part of a time zone. Many time zones alternate between two different offsets to account for daylight saving time. The time zone has to account for this, including the specific dates and times that daylight saving time begins and ends, as well as any history of changes that the time zone may have had.
The New Zealand case you gave is a perfect example. You said "12 is New Zealand timezone", and thus expected since New Zealand is in DST for that date that the conversion from 6:14 UTC to New Zealand local time would be 19:14. - 13 hours later.
But 12 doesn't fully represent New Zealand. It is just a 12 hour offset from UTC. There are plenty of other time zones that use the same offset in different ways. For example, the Marshal Islands use UTC+12 year round, without daylight saving time.
You should really read the timezone tag wiki - especially the section titled "Time Zone != Offset".
Instead of offsets, you should represent time zones with their full IANA identifier from the tz database. For example US Eastern Time is "America/New_York", Indian Time is "Asia/Kolkata", and New Zealand Time is "Pacific/Auckland". You can find more in the list on Wikipedia.
You can use moment-timezone to work with these in JavaScript.
moment("2014-10-18T06:14:41.512Z").tz('Pacific/Auckland').format('YYYY-MM-DD HH:mm')
// Output: "2014-10-18 19:14"
I also cover these topics in great detail in my Date and Time Fundamentals course on Pluralsight.com.
Please Check this link
http://www.digitoffee.com/programming/get-local-time-utc-using-moment-js/94/
var timezone = "UTC+5.30";
var utcDate = "2014-10-19T10:31:59.0537721Z";
var localDate = moment.utc(utcDate).tz(timezone).format()
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
I've been looking for days to find how to get moment.js to behave correctly and return the correct date for a specific local time zone.
Here is my challenge:
I'm calling a flight api to get the "arrival date/time" of a flight. It provides me the arrival time in epoch time and a timezone for the airport.
I'm using javascript moment.js to convert that to the local time of the airport, BUT, the time always comes in a couple days ahead.
Here's my code:
var dateVal = 1395184260;
var day = moment.unix(dateVal).tz('America/Vancouver').format();
console.log("tz :",day);
// should return: 4:21 PM - Sun Mar-16-2014 BUT it always returns the 18th instead of the 16th.
Where are you getting the "should return" from?
According to http://www.epochconverter.com/epoch/timezones.php?epoch=1395184260, your time should be
Mar 18 2014 16:11:00 GMT-7:00
This fiddle using your timestamp:
var dateVal = 1395184260;
var date = moment.unix(dateVal);
console.log(date.tz("America/Vancouver").format('ll HH:mm:ss Z'))
returns:
Mar 18 2014 16:11:00 -07:00
I'd check whatever converter you're using to see if there's a bug.