How to convert a UTC time to local time javascript - javascript

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()

Related

Creating Date by iso ''0001-01-01T01:00:00' adding 16 second

new Date("0001-01-01T01:00:00Z") --> Mon Jan 01 0001 02:50:16 GMT+0150 (Moscow Standard Time)
Incorrect GMT: my timezone GMT+3000, but date creates GMT+0150
For dates, you can (and should, in my opinion) define them in UTC ISO 8601 "Z" format ("YYYY-MM-DDTHH:MM:SSZ"), just as you did.
However, to get a user-friendly string representation of those dates, it will depend on your client and on the Javascript engine used. You can constrain the output if you explicitly specify a reference timezone with toLocaleString().
var date = new Date("1990-01-01T01:00:00Z");
console.log(date.toLocaleString("en-US", {timeZone: "Asia/Jerusalem"}));
console.log(date.toLocaleString("en-US", {timeZone: "Europe/Moscow"}));
console.log(date.toLocaleString("en-US", {timeZone: "Africa/Djibouti"}));
// output on my machine, should be the same on yours :
// 1/1/1990, 3:00:00 AM
// 1/1/1990, 4:00:00 AM
// 1/1/1990, 4:00:00 AM
console.log(date.toString());
// output **on my machine**, should **not** be the same on yours
// Mon Jan 01 1990 02:00:00 GMT+0100 (Central European Standard Time)
For the 16 seconds issue, this is linked to the way offset are defined by the rules for those dates before the notion of IANA timezone existed.
They probably don't make sense in your application, and I discourage you to use dates like 1st January of year 0001 for your examples.
Examples :
var date = new Date("0001-01-01T01:00:00Z");
console.log(date.toLocaleString("en-US", {timeZone: "Asia/Jerusalem"}));
console.log(date.toLocaleString("en-US", {timeZone: "Europe/Moscow"}));
console.log(date.toLocaleString("en-US", {timeZone: "Africa/Djibouti"}));
// output on my machine, should be the same on yours :
// 1/1/1, 3:20:54 AM
// 1/1/1, 3:30:17 AM
// 1/1/1, 3:27:16 AM
console.log(date.toString());
// output **on my machine**, should **not** be the same on yours
// Mon Jan 01 0001 01:09:21 GMT+0009 (Central European Standard Time)
More information here (thanks Johan Karlsson for the link) :
https://bugs.chromium.org/p/chromium/issues/detail?id=849404
The most relevant comment from this link is, I think :
This is working as intended and working per spec. The spec says that
we have to follow the IANA timezone database.
In 1880, there's no standard timezone and America/Los_Angeles timezone
offset was based on its longitude. The same is true of other
timezones.
Also note that there are many timezone around the world the zone
offset (and whether or not to have DST or when to start DST) have
changed multiple times even since 2000 (e.g. Europe/Moscow). The
change to make them work correctly also brought in what's reported
here.
Pac0's answer is correct (and you should accept that answer since it came first, not this one). But just to provide a detailed explanation:
Dates from before recorded history of time zones are marked in the time zone database as LMT - which stands for Local Mean Time. The offsets are derived from the latitude and longitude of the city, not by any current political determination.
Since the offset shown is 1:50:16 ahead of UTC, I can derive that your system time zone is Europe/Minsk. This is seen in the tzdb sources here:
# Zone NAME GMTOFF RULES FORMAT [UNTIL]
Zone Europe/Minsk 1:50:16 - LMT 1880
This is just the first line of the zone entry for Europe/Minsk, which says that until 1880, use the LMT entry of UTC+1:50:16.
As to why it says "Moscow Standard Time" - that string comes from the Unicode CLDR data, which in the /common/supplemental/metaZones.xml file we can see:
<timezone type="Europe/Minsk">
<usesMetazone to="1991-03-30 23:00" mzone="Moscow"/>
<usesMetazone to="2011-03-27 00:00" from="1991-03-30 23:00" mzone="Europe_Eastern"/>
<usesMetazone to="2014-10-26 22:00" from="2011-03-27 00:00" mzone="Europe_Further_Eastern"/>
<usesMetazone from="2014-10-26 22:00" mzone="Moscow"/>
</timezone>
So Europe/Minsk uses the Moscow metazone up until 1991. Then, using one of the language files such as /common/main/en.xml for English, we can see the actual text assigned to this metazone:
<metazone type="Moscow">
<long>
<generic>Moscow Time</generic>
<standard>Moscow Standard Time</standard>
<daylight>Moscow Summer Time</daylight>
</long>
</metazone>
And now you have a complete picture for how the string Mon Jan 01 0001 02:50:16 GMT+0150 (Moscow Standard Time) was derived from 0001-01-01T01:00:00Z.
A timezone is an offset plus a date range. To format your date, javascript wants to know what the timezone offset was for Moscow in the year zero. This is hard information to come by, and might not be accurate ! You think you're asking something simple, but it's actually pretty extreme. If you want to use the date object to represent durations, you should take the epoch as your starting point.

Why in javascript, creating date between 1st October 1941 and 14th October 1945 adding GMT+0630 as time zone

My Time Zone is (UTC +05:30)Chennai, Kolkata, Mumbai, New Delhi.
For Example:
var date1 = new Date(1944,04,22,0,0,0);
console.log("date1: " + date1);
// output :
// date1: Mon May 22 1944 00:00:00 GMT+0630 (India Standard Time)
var date2 = new Date(1992,11,28,0,0,0);
console.log("date2: " + date2);
// output :
// date2: Mon Dec 28 1992 00:00:00 GMT+0530 (India Standard Time)
date1 is adding GMT+0630 at the end. But if I will take a date after 1945 then it is fine i.e it adds GMT+0530.
Why one extra hour is getting added in Time zone for dates between 1st October 1941 and 14th October 1945.
When i convert date1 in C# with:
Convert.ToDateTime("1944-05-21T17:30:00.000Z").ToString("dd/MM/yyyy");
It gives me 21/05/1944 instead of 22/05/1944.
How can i get correct Date and Time in C#?
A few things:
Indeed, India did use UTC+6:30 for several periods in the 1940's. This information is recorded in the IANA time zone database. You can also refer to the detail of time in India here.
.NET (when running on Windows) does not use the IANA time zone database, but rather the Microsoft Windows time zone database. You can read about some of the differences between these two data sets in the timezone tag wiki.
The Windows time zone database generally does not have the long term history of most time zones. For India Standard Time, it doesn't have any history - assuming that UTC+5:30 has always been in effect. If your application needs to know about historical time zone information, then you have two options:
If you are using .NET Core, you can run on a non-Windows OS (Linux, MacOS, etc.) which uses the full IANA time zone database. The standard TimeZoneInfo, DateTime, and DateTimeOffset APIs will use this data on non-Windows machines.
You can bring your own copy of the IANA TZDB data via a library such as Noda Time. Then you can run on any OS you want. Of course, you will need to stay updated to get changes to the TZDB.
A Noda Time example for your scenario looks like this:
Instant utcTime = Instant.FromUtc(1944, 5, 21, 17, 30);
DateTimeZone tz = DateTimeZoneProviders.Tzdb["Asia/Kolkata"];
ZonedDateTime zdt = utcTime.InZone(tz);
LocalDateTime ldt = zdt.LocalDateTime;
Console.WriteLine(ldt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
There are, of course, shorter ways to write this - and APIs within NodaTime for parsing, formatting, manipulation, conversion etc. But I think you get the point.

given a timezone string, how can i set a date object to that TZ in JS

I have this code:
toolFilters.filter('dateAccordingToTimeZone', function($filter) {
// Gets the number of milliseconds pass from 1970 and convert it to time according to given timezone, currently
// supported “Asia/Jerusalem” and “America/Los_Angeles”
return function(milliSeconds, timeZoneId) {
if (milliSeconds == 0) {
return "";
}
var d = new Date();
var n = d.getTimezoneOffset();
if ((timeZoneId == "Asia/Jerusalem") || (timeZoneId == "IL")) {
return $filter('date')(milliSeconds, 'MMM d, y H:mm:ss', '+0200');
} else if ((timeZoneId == "America/Los_Angeles")) {
return $filter('date')(milliSeconds, 'MMM d, y H:mm:ss', 'PST');
} else {
return $filter('date')(milliSeconds, 'MMM d, y H:mm:ss');
}
};
})
I try to make it more generic, so I created a Date() object but I cannot set its TZ with the given TZ string. How can I do it?
Then I want to use getTimezoneOffset()
Provided the timezone string is a valid IANA timezone identifier and the Intl object is supported, you can use Date.prototype.toLocaleString with an appropriate language code, e.g.
var d = new Date();
console.log(d.toLocaleString('en-GB', {timeZone:'America/Los_Angeles', timeZoneName:'short'}));
console.log(d.toLocaleString('en-GB', {timeZone:'Asia/Jerusalem', timeZoneName:'short'}));
console.log(d.toLocaleString('en-GB', {timeZone:'UTC', timeZoneName:'short'}));
Otherwise, you'll need to use a library. Writing your own function to support all regions, timezones and daylight saving shifts is likely not reasonable, though the IANA timezone database is freely available if you wish to do that.
TLDR;
An offset is simply the difference between a local time (however that is determined) and UTC. A timezone is a region that observes the same timezone offset. The region and offset are typically determined by some administrative body such as a regional or national government.
A particular place may be in more than one timezone and have more than one offset depending on the date, e.g. Sydney, Australia uses Australian Eastern Standard Time (AEST) which is UTC+1000 during winter and Australian Eastern Daylight Time (AEDT) which is UTC+1100 during summer, so two different offsets and two different timezones. Brisbane, Australia uses AEST all year round, so one offset and one timezone. Perth, Australia, has dabbled with daylight saving from time to time. Norfolk Island changed its offset from +11:12 in 1951, then to +1030 to +11:00 in 2015, and observed daylight saving for year in the 1970s.
There is no standard for naming timezones, though the IANA names are becoming a de facto standard. There is also no way to reliably determine the timezone from the offset, though a reasonable guess can be made based on summer and winter offsets that is correct most of the time (but that will not do in a general case where it must be correct).
Typically, dates are exchanged using UTC (zero offset), with an adjustment made for display purposes only. This can create issues where the offset should be ignored, e.g. birthdays. Someone born in India at 04:30 in the morning of 1 Jan 2018 does not, when in New York, say they were born on 31 Dec 2017, even though that was the date in New York at the moment they were born.

What format is this timestamp, and how can I format it in its own time

I have a problem converting a timestamp in javascript.
I have this timestamp:
2011-10-26T12:00:00-04:00
I have been trying to format it to be readable. So far, it converts this using the local time of my system instead of the GMT offset in the timestamp. I know the timezone that this was created in is EST. I'm in PST, so the times are being offset by 3 hours.
Instead of this showing as:
Wednesday October 26, 2011 12:00 pm
It shows as:
Wednesday October 26, 2011 9:00 am
I have tried a few different solutions, but the latest one is found here: http://blog.stevenlevithan.com/archives/date-time-format
I am less concerned with the formatting part as I am with figuring out how to handle the GMT offsets. Would appreciate any help and insight anyone can provide.
Date objects are created in the local zone. If the date string was created in a different time zone, then you need to adjust the date object to allow for the difference.
The abbreviations PST and EST are ambiguous on the web, there is no standard for time zone abbreviations and some represent two or zones. You should express your zone only in terms of +/- UTC or GMT (which are the same thing, more or less).
You can get the local time zone offset using Date.prototype.getTimezoneOffset, which returns the offset in minutes that must be added to a local time to get UTC. Calculate the offset for where the time string was created and apply it to the created date object (simply add or subtract the difference in minutes as appropriate).
If your time zone is -3hrs, getTimezoneOffset will return +180 for a date object created in that zone. If the string is from a zone -4hrs, its offset is +240. So you can do:
var localDate = new Date('2011-10-26T12:00:00') // date from string;
var originOffset = 240;
var localOffset = localDate.getTimezoneOffset();
localDate.setMinutes( localDate.getMinutes() + originOffset - localOffset );
Adding the origin offset sets it to UTC, subracting the local offset sets it to local time.
It would be much easier if the time string that was sent by the server was in UTC, that way you just apply the local offset.
Edit
IE will not parse a time string with an offset, and Chrome thinks that the above time string is UTC and adjusts for local offset. So don't let Date parse the string, do it manually.
It doesn't matter what time zone you are- the time stamp will result in a different local time for every different time-zone, but they all will be correct, and anyone checking the UTC time of the date will get the same time-stamp:
new Date('2011-10-26T12:00:00-04:00').toUTCString()
returns
Wed, 26 Oct 2011 16:00:00 GMT
and getTime() anywhere returns the same milliseconds universal timestamp:1319644800000

Setting Javascript date object to midnight without being based on user computer date

I need to set a date and time to 12 midnight regardless of the user's computer date. I am creating an international meeting planner to offset time zones to get the meeting.
I have it working but I need to code now the differences in time zones. If I use new Date, it gives me the time based on the user's computer. For example, mine is Eastern US. If I try to do the time zone shift on November 6, 2011, Javascript/computer will calculate MY time zone shift at 2am. I do not want this.
My real goal is to set it to 12 midnight in the timezone that is where the meeting will be hosted from (let's say Afghanistan) and then calculate from there.
So:
How do I set 12 midnight without being being the user's computer time?
Can I set 12 midnight to a specific time zone, without being dependent on user's computer time?
I have to do this with Javascript as there is no server code involved.
Thanks
Something like this I would guess: new Date(Date.UTC(year, month, day, hour, minute, second))
w3schools Reference
To create midnight in GMT:
// Note: months are 0-based, so 7 == august
var midnight = new Date( Date.UTC(2011,7,15) );
// Sun Aug 14 2011 18:00:00 GMT-0600 (Mountain Daylight Time)
To create midnight in another time zone:
var mdt = -6; // Mountain Daylight Time
var midnightMDT = new Date( Date.UTC(2011,7,15,-mdt) );
//-> Mon Aug 15 2011 00:00:00 GMT-0600 (Mountain Daylight Time)
Date objects are expressed in the local time zone of the user, but they are still representative of midnight in another time zone.
If you want to express a date in another time zone, you'll need to offset the date to that timezone (setUTCHours()) and then use the various getUTC* methods (e.g. getUTCHours()) to construct your own string.

Categories