What do the getUTC* methods on the date object do? - javascript

What does it mean when you get or create a date in UTC format in JavaScript?

A date represents a specific point in time. This point in time will be called differently in different places. As I write this, it's 00:27 on Tuesday in Germany, 23:27 on Monday in the UK and 18:27 on Monday in New York.
To take an example method: getDay returns the day of the week in the local timezone. Right now, for a user in Germany, it would return 2. For a user in the UK or US, it would return 1. In an hour's time, it will return 2 for the user in the UK (because it will then be 00:27 on Tuesday there).
The ..UTC.. methods deal with the representation of the time in UTC (also known as GMT). In winter, this is the same timezone as the UK, in summer it's an hour behind the time in the UK.
It's summer as I write this. getUTCDay will return 1 (Monday), getUTCHours will return 22, getUTCMinutes will return 27. So it's 22:27 on Monday in the UTC timezone. Whereas the plain get... functions will return different values depending on where the user is, the getUTC.. functions will return those same values no matter where the user is.

getUTC is for converting times to Coordinated Universal Time (UTC, the acronym is ordered differently than what it stands for) which is the standard time based on the time in Greenwich, London.
The universal time is calculated using a time offset (in minutes when in JavaScript.) This offset is based on the time zone configured on the client browser's operating system.
If you plan on storing dates for users in multiple time zones, this is what you should use.

Further to Dan's remark about the acronym being different to what it stands for is a good reason: UTC Abbreviation on Wikipedia

Related

Differences in dates between .Net and Javascript

I had an issue where dates were out by one day when displaying on an asp.net web form. These dates are only used for display so I can pass them as strings to resolved the issue, but I'm curious about why I'm seeing this behaviour.
I'm in Ireland, and while Ireland is more or less in line with GMT, we use IST (Irish Standard Time) during summer instead of DST and then revert to GMT for Winter. This has the same effect as being on GMT, but "officially" is slightly different.
As we're not on GMT, in the past, IST and DST didn't always line up.
For example, in 1958, IST started in the 20th April and ended on the 5th October whereas, DST started on the 27th of April and ended on 26th of October.
So if a date between the 5th and 26th of October 1958 is passed to JS, JS will display it as the previous day.
I wrote this this code to try and understand what's going on:
DateTime date = new DateTime(1958, 10, 4);
while (date <= new DateTime(1958, 10, 30))
{
Console.WriteLine($"normal : {date} | isDst? : {date.IsDaylightSavingTime()}");
Console.WriteLine($"universal: {date.ToUniversalTime()} | isDst? : {date.ToUniversalTime().IsDaylightSavingTime()}");
Console.WriteLine($"local : {date.ToLocalTime()} | isDst? : {date.ToLocalTime().IsDaylightSavingTime()}");
Console.WriteLine("-------------------------");
date = date.AddDays(1);
}
Which produced this output (truncated):
So I can see there are a number of days being mis identified as DST days, but it doesn't seem like that would cause this? If both .Net and JS though they were DST days, then surely the end result should be correct?
Additionally, why is there a 2 hour difference between the output of ToUniversalTime and ToLocalTime during DST?
Here's a screenshot of JS processing a few dates duirng this problematic window
You can see that JS (or chrome?) is aware that during the 5th to the 27th of that year, Ireland is no longer on GMT+1 (even though it still says it's IST) so why is the date passed from VB an incorrect date? I though they both got their datetime information from the same source i.e. the host pc?
You appear to be running .NET on Windows, in which case .NET is using the Windows time zone data for your local time zone.
The Windows time zone data does not have the full history of time zone changes from all time. Microsoft's policy only guarantees historical data is present for dates from 2010 forward, though some time zones have historical data before then.
Conversely, Chrome is using time zone data from ICU, which uses IANA time zone data. IANA time zones have historical data since at least 1970, though many time zones have historical data before then.
With specific regard to Ireland, IANA has Irish time zone data going back to 1880. Windows has no history for Ireland at all, so it assumes the current rule has always been in effect. In reality, the current rule has been in effect since Oct 1968, so any dates before then will only have accurate time zone information in the IANA data.
If you run the same .NET code you showed above on Linux or MacOS, you'll see that .NET will use IANA time zone data on those platforms and your results will match up for 1958. Or, if you pick a more recent date your results will match on Windows too.
In short - don't run these sorts of tests on old dates and expect to get the same fidelity that you'll get with modern dates.
You also asked:
Additionally, why is there a 2 hour difference between the output of ToUniversalTime and ToLocalTime during DST?
Your date variables are all DateTime where .Kind is DateTimeKind.Unspecified. The IsDaylightSavingTime method will treat such values as if they belonged to the local time zone, as if they actually had DateTimeKind.Local. The same is true for the ToUniversalTime method, however, the ToLocalTime method will assume that DateTime values with DateTimeKind.Unspecified kind are actually in terms of UTC - as if they were DateTimeKind.Utc. Thus, when DST is in effect, date.ToUniversalTime() shifts an hour backward, and date.ToLocalTime() shifts an hour forward.
You can avoid such ambiguities by using DateTimeOffset instead of DateTime.

Why the difference between 2 time stamps has one hour deviation compared to expected value?

Take the date '2022-04-01' and another date '2022-05-15' for example. When I calculated their deviation in Chrome devtools, what I got is:
The result is 3801600000. But when my friend did the same thing in another device, what he got is:
The result is 3798000000. The difference between 3801600000 and 3798000000 is exactly one hour. What may causes this result? How can I eliminate this difference?
You lack the zone data:
UTC datetime: new Date("2021-01-01T12:00:00Z");
UTC-4 datetime: new Date("2021-01-01T12:00:00-04:00");
The main issue you are experiencing is because your input string is being interpreted as assigned to the local time zone, and you have different time zones on the two machines you've been testing with. One of them has a DST transition between the two dates, and the other does not - which explains your one hour difference.
The examples you show also reveal your possible time zones:
Your machine is showing 8 hours ahead of UTC (UTC+8) for both timestamps. There are several parts of the world that use UTC+8 without DST, including China, Western Australia, Irkutsk Russia, and many others. There are no places on earth that use UTC+8 in conjunction with DST.
Your friend's machine is a different story. The timestamps are showing 2 hours ahead of UTC (UTC+2) on 2022-04-01, and 3 hours ahead of UTC (UTC+3) on 2022-05-15. While many countries use those offsets (such as those that are in Eastern Europe that use EET/EEST), none of those areas have a DST transition between those two dates. See the bottom of this table of DST transitions. All of the +2/+3 areas of the world transitioned in March. I can only conclude that your friend's machine has some non-standard time zone setting, or they are significantly behind on time zone data updates, or both. (Please reply in comments if I am incorrect on this!)
Also, your input string format, 2022-04-01 00:00:00 is not in the standard date time string format defined by the ECMAScript specification. Thus, it is not guaranteed to be parsed consistently by all browsers. Current versions of Chrome, Edge, and Firefox will interpret it as a local date and time, but the current version of Safari will fail with "Invalid Date".
If you want it interpreted as local time correctly in all browsers, you would need to specify it as 2044-04-01T00:00:00.
If you want it interpreted as UTC then specify as 2044-04-01T00:00:00Z.
If you want it interpreted with a specific time zone offset, then append that instead, as in: 2044-04-01T00:00:00+08:00.
If you must parse the string in the original format, then don't do it using the Date object. Either use a library (such as Luxon or date-fns), or parse it yourself with regex and/or string manipulation techniques.

How to maintain Timezone

My client is in india and server in USA . If user submit his post from india it get stored in USA server so when i display post submit time to user it is as per USA time . I want to show it as per clients timezone
The simplest way to handle timezones is to work with Epoch time behind the scenes, and translate it to the user's preferred timezone on render (or with client-side code).
Epoch time is the number of seconds since it became 1 January 1970 in London. For example, right now the time is 1483130714. This means we've got one simple number, that can be effortlessly compared and sorted, to represent precise moments without needing to care about dates, timezones, locales and their frustrating details. Virtually all languages in popular use have the ability to parse these numbers into their own timestamp values. In JavaScript, you can do this with new Date(1483130714). You'll get a date object and you can then present that however you like (eg with toLocaleString).
If you don't use Epoch time, you'd want to use UTC, the next-best thing. The important thing is to store in a consistent universally-understood format and then translate it to the user's preferred form as needed.
You need to store date in UTC and then convert it as per browser culture and timezone. So store all dates in UTC and depending on browser culture you can add offset, this could be tricky if user sets wrong culture and time.

Get UTC Offset from date with different timezone

Im struggling with date issues and would love to get some help.
i want to get to offset from UTC by the timezone name.
I am getting my date from the server in this format:
"July 11, 2016::11:09:43 AM IDT" (Time Zone in this case is IDT- but can be any other timezone).
I want to be able to get the offset from IDT (in this case) to UTC.
Is there any way to figure it out?
thanks!
livnat:)
If you examine a list of time zone abbreviations and their corresponding offsets, such as the list on Wikipedia or the list on timeanddate.com, you may be able to find that IDT is an abbreviation for Israel Daylight Time, and is equal to UTC+3. However, upon further examination you'll also find that there are many abbreviations that are ambiguous. For example:
CST could be any of:
Central Standard Time (UTC-6)
China Standard Time (UTC+8)
Cuba Standard Time (UTC-5)
BST could be any of:
British Summer Time (UTC+1)
Bangladesh Standard Time (UTC+6)
Bougainville Standard Time (UTC+11)
... and many others.
You'll also find that two lists I mentioned are not identical. That's because in general, time zone abbreviations are a convention, not a standard.
Therefore, if all you have is an abbreviation, and you want to cover all the time zones of the world, then you cannot uniquely identify the time zone.
That said, if you can limit your list to a set of predefined, non-conflicting abbreviations, then you could certainly work out a mapping table on your own. Alternatively, if you have additional information such as the country, then you can also use that information to disambiguate.

Date of birth: Same date of birth in every local?

Currently im storing the date of birth of a user in milliseconds (since 01.01.1970). Do i have to ensure that it is the same date of birth in every country or is it common that it can happen that it is the 11th November in country X and the 12th November in country Y?
If instead it is common practice to have the exact same date of birth in each country, how could i ensure that the milliseconds i store always point to the exact same day of month in each country?
Ignore time-of-day
Few people know the time-of-day of their birth. So, no, that level of detail is not commonly tracked. You never see time-of-birth and birth-time-zone on passports and such. They track a date-only value, without time of day and without time zone.
Bartenders, border control agents, etc. use the local current date to calculate age, with no attempt to consider time of day or adjust for time zone. Consider that partial-day difference to be truncated, ignored.
To adjust a moment accurately from one time zone to another, you need a date and a time-of-day. Without a time-of-day you have perhaps 23-25 hours of possible moments when their birth may have occurred.
For example, a birth that occurs a few minutes after midnight in Paris (1 or 2 hours ahead of UTC) on the 24th is still “yesterday” the 23rd in Montréal (4 or 5 hours behind UTC). But if that birth occurs at 06:00 in the 24th, then the date is the same (24th) in both Paris & Montreal, but is “yesterday” (23rd) in Vancouver BC and Seattle where the clocks are 7 or 8 hours behind UTC.
SQL
In SQL use a data type akin to the standard DATE type.
Java
In Java, use the LocalDate type. To represent the recurring month and day of the birthday celebration, use the MonthDay class.
For interacting with a database, drivers that comply with JDBC 4.2 should be able to work directly with LocalDate via the getObject & setObject methods on a PreparedStatement. If not, fall back to using the old java.sql.Date. New methods added to that old class facilitate conversion.
ISO 8601
When generating string representations of date-time values, use the formats defined in the ISO 8601 standard such as YYYY-MM-DD, ex: 1960-07-11. For date without year use --MM-DD, ex: --07-11. The java.time classes in Java use ISO 8601 formats by default when parsing and generating Strings.
Forcing time-of-day
If for some reason you are forced to put a date-only value into a date-time field, then you must set some arbitrary time-of-day. Noon is one possibility. I suggest setting the time portion to the first moment of the day.
First moment of the day
Be aware that the first moment is not always 00:00:00. Daylight Saving Time (DST) and perhaps other anomalies affect midnight in some time zones. So first moment of the day might be 01:00:00 for example. Java can determine the first moment of the day appropriate to a particular time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
ZonedDateTime startOfToday = today.atStartOfDay( zoneId );
It is up to you to decide what time zone to interpret a selected date of birth as and what time zone to use when displaying the date of birth. In my opinion, it is logical to always use the timezone of the place of birth (if you wish to collect that) when converting the date of birth from a timestamp to readable form and when storing it. Otherwise, you can always use GMT or any other timezone as your convention. This will ensure that all users in all countries will see the same date of birth but it is recommended to append the time zone to the date representation to prevent confusion. You may of course choose to interpret dates as GMT based when creating the timestamp to store and then render the date of birth using a user-defined timezone (possibly timezone for the user's account). In this case, the date (and time if you include the time of birth) will appear different for each user.

Categories

Resources