I'm determining the difference between two calendar dates in Javascript in an Ember app. I'm currently using date-fns's differenceInCalendarDays.
Now that mostly provides the desired results, the only issue is that I need to handle calculating the difference between 2 dates that is sensitive to a timezone (not the local timezone to the browser).
As far as I'm aware JS Dates are tracked as UTC, with no timezone stored on the date object itself. Any timezone localization I've done in JS has been outputting a string.
Is there a good library or way to accomplish differenceInCalendarDays while taking into account the timezone?
const daysAgo = this.intl.formatRelative(-differenceInCalendarDays(new Date(), someOtherDay), {
unit: 'day',
numeric: 'auto',
timeZone: 'this.intl.timeZone
});
This is a small sample of what I'm doing, obviously differenceInCalendarDays will resolve to a number which won't take into account any timeZone. The docs for differenceInDays is timezone sensitive to the browser's local time (which is not helpful here), but differenceInCalendarDays makes no such mention.
Any help would be greatly appreciated!
Logically, the difference between two calendar dates such as 2020-01-01 and 2020-01-02 is not time zone sensitive, nor does it involve time at all. It is exactly one day. In this context a day is not 24 hours, but rather it is a logical division of a year. Think of it as a square on a paper calendar.
However - at any given instant two different time zones might be on the same calendar date, or they might be on two different calendar dates. Thus, a time zone matters when determining the date that it is "now" (or "today", "yesterday", "tomorrow", etc.)
To illustrate both points and hopefully answer your question, the following code can be used to get the number of days passed since "today" in a given time zone:
function daysSince(year, month, day, timeZone) {
// Create a DateTimeFormat object for the given time zone.
// Force 'en' for English to prevent issues with languages that don't use Arabic numerals.
const formatter = new Intl.DateTimeFormat('en', { timeZone });
// Format "now" to a parts array, then pull out each part.
const todayParts = formatter.formatToParts(); // now is the default when no Date object is passed.
const todayYear = todayParts.find(x=> x.type === 'year').value;
const todayMonth = todayParts.find(x=> x.type === 'month').value;
const todayDay = todayParts.find(x=> x.type === 'day').value;
// Make a pseudo-timestamp from those parts, abusing Date.UTC.
// Note we are intentionally lying - this is not actually UTC or a Unix/Epoch timestamp.
const todayTimestamp = Date.UTC(+todayYear, todayMonth-1, +todayDay);
// Make another timestamp from the function input values using the same approach.
const otherTimestamp = Date.UTC(+year, month-1, +day);
// Since the context is the same, we can subtract and divide to get number of days.
return (todayTimestamp - otherTimestamp) / 864e5;
}
// example usage:
console.log("US Pacific: " + daysSince(2020, 1, 1, 'America/Los_Angeles'));
console.log("Japan: " + daysSince(2020, 1, 1, 'Asia/Tokyo'));
This approach only works because UTC doesn't have transitions (such as DST or changes in standard time offset).
Also note that I don't use Date objects here, because we'd have to be very careful about how those objects were constructed. If you only have a Date object coming from a date picker UI, that object was likely created assuming local time - not the time in a particular time zone. So, you'll want to pull out the year, month, and day from that object before continuing. For example:
daysSince(dt.getFullYear(), dt.getMonth() + 1, dt.getDate(), 'America/New_York');
Pay close attention to +1 and -1. The Date object uses 0-based months, but I prefer 1-based.
Related
I am working on a angular project.
I want to the start time and off time of a office in a table.
Example : 8:30 - 17:30
The office has two branches in UK and India.
So user may enter time in UK time or Indian time. But I am going to store the time in GMT time.
SO I want to give an option to select the time zone and enter the time.
Then I have to convert then that time into GMT time and send to database.
How can I convert UK time to GMT time?
Or do you know any idea to do this scenario Please advice me.
Thank you
ECMAScript Date instances don't have a timezone, they are inherently UTC. System settings are used for default toString plus get and set methods so they appear to be local.
Also, the parser is very basic and is generally to be avoided other than for parsing the exact format specified for toISOString.
You should also see How to initialize a JavaScript Date to a particular time zone, which might be a duplicate for this question.
The best way to achieve what you're after (until the Temporal object is widely supported) is to use a library. There are a number of libraries that work with timezones, the following uses Luxon.
// Alias
let DateTime = luxon.DateTime;
// Create a date for now in London
let ukDate = DateTime.now().setZone('Europe/London');
// Set it to the required time
let ukOpenTime = ukDate.set({hour:8, minute:30, second:0, millisecond: 0});
console.log('ukOpenTime as string :' + ukOpenTime.toString());
// Get time value to store
let millis = ukOpenTime.toMillis();
console.log('ukOpenTime as time value: ' + millis);
// Show equivalent local time in numerous ways
// Shift ukOpenTime to local zone: default is the local (system) timezone
let localOpenTime = ukOpenTime.setZone();
console.log('Equivalent local time 1 : ' + localOpenTime.toString());
// Use the time value (millis) to create a new Luxon object
let localOpenTime2 = DateTime.fromMillis(millis);
console.log('Equivalent local time 2 : ' + localOpenTime2.toString());
// Use the time value (millis) to create a plain date
let localOpenTime3 = new Date(millis);
console.log('Equivalent local time 3 : ' + localOpenTime3.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>
why not store it in Epoch Time and convert it every time? like 1659755549?
or use epoch as intermediate for calculation
p.s. no rep for comments :(
This question is related to this question.
So if we construct a date using an ISO string like this:
new Date("2000-01-01")
Depending on what timezone we are in, we might get a different year and day.
I need to be able to construct dates in Javascript that that always have the correct year, day, and month indicated in a string like 2000-01-01, and based on the answer in one of the questions if we use back slashes instead like this:
const d = new Date("2000/01/01")
Then we will always get the right year, day, and month when using the corresponding date API methods like this:
d2.getDate();
d2.getDay();
d2.getMonth();
d2.getFullYear();
So I just wanted to verify that my understanding is correct?
Ultimately I need to be able to create Date instances like this for example:
const d3 = new Date('2010/01/01');
d3.setHours(0, 0, 0, 0);
And the time components should always be zero, and the year, month, and day should be the numbers specified in the string.
Thoughts?
I just did a quick test with this:
https://stackblitz.com/edit/typescript-eztrai
const date = new Date('2000/01/01');
console.log(`The day is ${date.getDate()}`);
const date1 = new Date('2000-01-01');
console.log(`The day is ${date1.getDate()}`);
And it logs this:
The day is 1
The day is 31
So it seems like using backslashes should work ...
Or perhaps using the year, month (0 based index), and day constructor values like this:
const date3 = new Date(2000, 0, 1);
date3.setHours(0, 0, 0, 0);
console.log(`The day is ${date3.getDate()}`);
console.log(`The date string is ${date3.toDateString()}`);
console.log(`The ISO string is ${date3.toISOString()}`);
console.log(`Get month ${date3.getMonth()} `);
console.log(`Get year ${date3.getFullYear()} `);
console.log(`Get day ${date3.getDate()} `);
NOTE
Runar mentioned something really important in the accepted answer comments. To get consistent results when using the Javascript Date API use methods like getUTCDate(). Which will give us 1 if the date string is 2000-01-01. The getDate() method could give us a different number ...
From the ECMA standard of the Date.parse method:
When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
What is happening is that New Date() implicitly calls Date.parse on the string. The "2000-01-01" version conforms to a Date Time String Format with a missing offset representation, so it is assumed you mean UTC.
When you use "2000/01/01" as input the standard has this to say:
If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
So in short the browser can do what they want. And in your case it assumes you mean the offset of the local time, so whichever offset you are located in gets added when you convert to UTC.
For consistent results, perhaps you want to take a look at Date.UTC
new Date(Date.UTC(2000, 0, 1))
If you need to pass in an ISO string make sure you include the time offset of +00:00 (is often abbreviated with z)
new Date("2000-01-01T00:00:00Z");
If you want to later set the date to something different, use an equivalent UTC setter method (e.g. setUTCHours).
When you retrieve the date, also make sure to use the UTC getter methods (e.g. getUTCMonth).
const date = new Date("2000-01-01T00:00:00Z");
console.log(date.getUTCDate());
console.log(date.getUTCMonth());
console.log(date.getUTCFullYear());
If you want to retrieve the date in a specific format you can take a look at Intl.DatTimeFormat, just remember to pass in timeZone: "UTC" to the options.
const date = new Date("2000-01-01T00:00:00Z");
const dateTimeFormat =
new Intl.DateTimeFormat("en-GB", { timeZone: "UTC" });
console.log(dateTimeFormat.format(date));
I am working on a cloud based application which deals extensively with date and time values, for users across the world.
Consider a scenario, in JavaScript, where my machine is in India (GMT+05:30), and I have to display a clock running in California's timezone (GMT-08:00).
In this case I have to get a new date object,
let india_date = new Date()
add it's time zone offset value,
let uts_ms = india_date.getTime() + india_date.getTimezoneOffset()
add california's timezone offset value,
let california_ms = utc_ms + getCaliforniaTimezoneOffsetMS()
and finally the date object.
let california_date: Date = new Date(california_ms)
Is there any way to directly deal with these kinds of time zones without having to convert the values again and again?
First, let's talk about the code in your question.
let india_date = new Date()
You have named this variable india_date, but the Date object will only reflect India if the code is run on a computer set to India's time zone. If it is run on a computer with a different time zone, it will reflect that time zone instead. Keep in mind that internally, the Date object only tracks a UTC based timestamp. The local time zone is applied when functions and properties that need local time are called - not when the Date object is created.
add it's timezone offset value
let uts_ms = india_date.getTime() + india_date.getTimezoneOffset()
This approach is incorrect. getTime() already returns a UTC based timestamp. You don't need to add your local offset. (also, the abbreviation is UTC, not UTS.)
Now add california's timezone offset value
let california_ms = utc_ms + getCaliforniaTimezoneOffsetMS()
Again, adding an offset is incorrect. Also, unlike India, California observes daylight saving time, so part of the year the offset will be 480 (UTC-8), and part of the year the offset will be 420 (UTC-7). Any function such as your getCaliforniatimezoneOffsetMS would need to have the timestamp passed in as a parameter to be effective.
and finally the date object
let california_date: Date = new Date(california_ms)
When the Date constructor is passed a numeric timestamp, it must be in terms of UTC. Passing it this california_ms timestamp is actually just picking a different point in time. You can't change the Date object's behavior to get it to use a different time zone just by adding or subtracting an offset. It will still use the local time zone of where it runs, for any function that requires a local time, such as .toString() and others.
There is only one scenario where this sort of adjustment makes sense, which is a technique known as "epoch shifting". The timestamp is adjusted to shift the base epoch away from the normal 1970-01-01T00:00:00Z, thus allowing one to take advantage of the Date object's UTC functions (such as getUTCHours and others). The catch is: once shifted, you can't ever use any of the local time functions on that Date object, or pass it to anything else that expects the Date object to be a normal one. Epoch shifting done right is what powers libraries like Moment.js. Here is another example of epoch shifting done correctly.
But in your example, you are shifting (twice in error) and then using the Date object as if it were normal and not shifted. This can only lead to errors, evident by the time zone shown in toString output, and will arise mathematically near any DST transitions of the local time zone and the intended target time zone. In general, you don't want to take this approach.
Instead, read my answer on How to initialize a JavaScript Date to a particular time zone. Your options are listed there. Thanks.
JavaScript Date objects store date and time in UTC but the toString() method is automatically called when the date is represented as a text value which displays the date and time in the browser's local time zone. So, when you want to convert a datetime to a time zone other than your local time, you are really converting from UTC to that time zone (not from your local time zone to another time zone).
If your use case is limited to specific browsers and you are flexible on formatting (since browsers may differ in how they display date string formats), then you may be able to use toLocaleString(), but browsers like Edge, Android webview, etc do not fully support the locales and options parameters.
Following example sets both the locale and timezone to output the date in a local format that may vary from browser to browser.
const dt = new Date();
const kolkata = dt.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' });
const la = dt.toLocaleString('en-US', { timeZone: 'America/Los_Angeles' });
console.log('Kolkata:', kolkata);
// example output: Kolkata: 19/3/2019, 7:36:26 pm
console.log('Los Angeles:', la);
// example output: Los Angeles: 3/19/2019, 7:06:26 AM
You could also use Moment.js and Moment Timezone to convert date and time to a time zone other than your local time zone. For example:
const dt = moment();
const kolkata = dt.tz('Asia/Kolkata').format();
const la = dt.tz('America/Los_Angeles').format();
console.log(kolkata);
// example output: 2019-03-19T19:37:11+05:30
console.log(la);
// example output: 2019-03-19T07:07:11-07:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
Well, you really do kind of have to convert anytime you want to change the display, but it's not as bad as you think.
First, store all time as UTC. Probably using the milliseconds format, e.g. Date.UTC().
Second, do all manipulation / comparison using that stored info.
Third, if your cloud-based application has an API that API should only talk in terms of UTC as well, though you could provide the ISO string if you prefer that to the MS, or if you expect clients to handle that better.
Fourth and finally, only in the UI should you do the final conversion to the local date/time string, either with the method you're describing or using a library such as momentjs
new Date creates a Date object with a time value that is UTC. If you can guarantee support for the timeZone option of toLocaleString (e.g. corporate environment with a controlled SOE), you can use it to construct a timestamp in any time zone and any format, but it can be a bit tedious. Support on the general web may be lacking. A library would be preferred in that case if you need it to work reliably.
E.g. to get values for California, you can use toLocaleString and "America/Los_Angeles" for the timeZone option:
var d = new Date();
// Use the default implementation format
console.log(d.toLocaleString(undefined, {timeZone:'America/Los_Angeles'}));
// Customised format
var weekday = d.toLocaleString(undefined, {weekday:'long', timeZone:'America/Los_Angeles'});
var day = d.toLocaleString(undefined, {day:'numeric', timeZone:'America/Los_Angeles'});
var month = d.toLocaleString(undefined, {month:'long', timeZone:'America/Los_Angeles'});
var year = d.toLocaleString(undefined, {year:'numeric', timeZone:'America/Los_Angeles'});
var hour = d.toLocaleString(undefined, {hour:'numeric',hour12: false, timeZone:'America/Los_Angeles'});
var minute = d.toLocaleString(undefined, {minute:'2-digit', timeZone:'America/Los_Angeles'});
var ap = hour > 11? 'pm' : 'am';
hour = ('0' + (hour % 12 || 12)).slice(-2);
console.log(`The time in Los Angeles is ${hour}:${minute} ${ap} on ${weekday}, ${day} ${month}, ${year}`);
Getting the timezone name is a little more difficult, it's difficult to get it without other information.
I've a list of timespan(object list actually), like 2:00, 15:00, 18:00 etc, it is in utc.
Now i want to convert this time slot back to CST and then sort it, as i want my time sorted in cst.
For timezone conversion i needed temporary date. so i choose current utc date by
moment.utc(mytimespan). and performed the timezone conversion by .tz("CST").
So list is converted to 20:00,9:00, 12:00
Here please note that i got 20:00 in first place instead of last place in the list.
This is due to date part of moment which went in back date.
All here i want is my timespan in sorted form without any effect of date.
please me to find a way to do it without string conversion!
Thanks
Update
my currently working code using string conversion
TimeSpanDetails.sort(function compare(a, b) {
return moment(moment.utc(a.startTime).tz("CST").format("HH:mm"),"HH:mm").isAfter(moment(moment.utc(b.startTime).tz("CST").format("HH:mm"),"HH:mm")) ? 1 : -1;
});
Now i want to do it without string conversion using format
A few things:
A "time span" usually refers to a duration of time, not a time-of-day. These are two very different concepts that are sometimes confused. Consider:
A timespan of 99 hours is perfectly valid, but "99:00" is nonsensical as a time-of-day.
Due to daylight saving time and other time zone transitions, a timespan can't necessarily be thought of as "time since midnight" because midnight may or may not exist, or some other hour of the day may be absent or repeated.
Time spans can be negative in some programing languages, usually representing a period before a given point in time.
The tz function in Moment.js takes IANA time zone names. You should not use CT or CST, but rather America/Chicago, for example. However, time zones are completely unrelated to time spans, so you should not be applying them at all. You do not need moment-timezone.
Moment represents time spans in Duration objects. You can parse them from strings like so:
var d = moment.duration('99:00');
Duration objects convert numerically to milliseconds, so they are comparable like so:
var a = moment.duration('00:00');
var b = moment.duration('01:00');
var c = a < b; //=> true
Moment does not have a strongly typed object for a time-of-day, but you can use Moment in UTC mode so that it does not have DST transitions, and then just let it use the current day. HOWEVER:
This would assume that all time-of-day values you have should be evaluated on the same date.
This may or may not be the case.
Consider that if all you have is time-of-day and don't know what dates they're from, then the values ['23:00', '00:00'] may be sorted already and only one hour apart, or perhaps they're out of sequence and they are 23 hours apart.
For sure, there is a lot of questions about Date objects and timezones but many of them are about converting the current time to another timezone, and others are not very clear about what they want to do.
I want to display the day, hour, minute etc. in an arbitrary timezone, in an arbitrary day. For example, I would like a function f(t, s) that:
given the timestamp 1357041600 (which is 2013/1/1 12:00:00 UTC) and the string "America/Los Angeles", would satisfy the comparison below:
f(1357041600, "America/Los Angeles") == "2013/01/01 04:00:00"
given the timestamp 1372680000 (2013/07/01 12:00:00 UTC), would satisfy the comparison below:
f(1357041600, "America/Los Angeles") == "2013/07/01 05:00:00"
will always behave this way even if the timezone in the browser is, let us say "Europe/London" or "America/São Paulo".
will always behave this way even if the time in the browser is, let us say 2014/02/05 19:32, or 2002/08/04 07:12; and
as a final restriction, will not request anything from the server side (because I'm almost doing it myself :) )
Is it even possible?
given the timestamp 1357041600 (which is 2013/1/1 12:00:00 UTC)
That appears to be seconds since the UNIX epoch (1970-01-01T00:00:00Z). Javascript uses the same epoch, but in milliseconds so to create a suitable date object:
var d = new Date(timestamp * 1000);
That will create a Date object with a suitable time value. You then need to determine the time zone offset using something like the IANA time zone database. That can be applied to the Date object using UTC methods. E.g. resolve the offset to minutes, then use:
d.setUTCMinutes(d.getUTCMinutes() + offset)
UTC methods can then be used to get the adjusted date and time values to create a string in whatever format you require:
var dateString = d.getUTCFullYear() + '/' + pad(d.getUTCMonth() + 1) + '/' ...
where pad is a function to add a leading zero to single digit values. Using UTC methods avoids any impact of local time zone offsets and daylight saving variances.
There are also libraries like timezone.js that can be used to determine the offset, however I have not used them so no endorsement is implied.
For JavaScript runtime environments that support the ECMAScript Internationalization API, and adhere to its recommendation of supporting the IANA time zone database, you can simply do this:
new Date(1357041600000).toLocaleString("en-US", {timeZone: "America/Los_Angeles"})
For other environments, a library is required. There are several listed here.