Create JavaScript Date object from date string + time string + timezone offset string - javascript

I have total 4 different input i.e.:
Date string (2020-05-05)
Time string (15:30)
Timezone offset (-09:00)
I want to combine these strings into one datetime object like (2020-05-05T15:30:00-09:00) no-matter what my local browser timezone is. The issue is when I combine these strings and I try to make date object using new Date() function, my datetime gets converted into UTC timestamp.
I tried this:
const date =
moment(this.actualDateOfSurgeryDate).format(YYYYMMDD) +
'T' +
moment(this.actualDateOfSurgeryTimeDropDown + ' ' + this.actualDateOfSurgeryTimeAM_PMDropDown, ['h:mm A']).format('HH:mm:ss') +
offsetTime;
this.caseDetail.actualDateOfSurgery = new Date(date);
This gives me output something like: 2020-05-05T04:30:00.000Z
How can I get my desired output: 2020-05-05T15:30:00-09:00 ??
I have moment js available in my project

I want to combine these strings into one datetime object like (2020-05-05T15:30:00-09:00)
Date objects are extremely simple, they're just a time value that is an offset in milliseconds since 1970-01-01T00:00:00Z, so are inherently UTC. The built–in parser is unreliable and lacks any functionality such as format tokens.
So if you have separate values like:
Date string (2020-05-05)
Time string (15:30)
Timezone offset (-09:00)
then you can create a string that is compliant with the format defined in ECMA-262 and that should be parsed correctly by the built–in parser, e.g.
new Date('2020-05-05T15:30:00.000-09:00')
However, general advice is to avoid the built–in parser due to differences in implementations. Also, the format must be exact (e.g. including seconds and milliseconds in the timestamp, colon (:) in the offset) or some implementations will reject it as malformed and return an invalid date.
Once you have a Date object, getting a "local" timestamp with offset is an issue of formatting, which has been answered many times before (e.g. How to format a JavaScript date). There aren't any decent built–in formatting functions (toLocaleString with options is OK for some purposes but generally lacking in functionality), so you'll have to either write your own function, or use a library.
The following examples use Luxon, which is suggested as the upgrade path from moment.js.
With Luxon, if you specify a representative location, you'll get the offset for that location at the date's date and time. Alternatively, you can fix the offset to a set value, essentially setting it for a timezone without a representative location, so it doesn't have any reference to daylight saving or historic offset changes:
let DateTime = luxon.DateTime;
// Offset per the specified location
let d0 = DateTime.fromISO('2020-01-01', {zone: 'America/Yakutat'});
let d1 = DateTime.fromISO('2020-06-30', {zone: 'America/Yakutat'});
console.log(d0.toString());
console.log(d1.toString());
// Fixed offset per the supplied string
let d2 = DateTime.fromISO('2020-05-05T15:30:00.000-09:00', { setZone: true});
let d3 = DateTime.fromISO('2020-01-01T15:30:00.000-09:00', { setZone: true});
console.log(d2.toString());
console.log(d3.toString());
<script src="https://cdn.jsdelivr.net/npm/luxon#1.24.1/build/global/luxon.min.js"></script>

I get 16:30 due to DST
A date before March or after October will give 15:30
let dateString = "2020-05-05"+"T"+"15:30"+":00"+"-09:00"
console.log(dateString)
const date = new Date(dateString)
console.log(date)
const Anchorage = date.toLocaleString('en-US', {timeZone: 'America/Anchorage', hour12: false})
console.log(Anchorage)
let options = {}
options.timeZone = 'America/Anchorage';
options.timeZoneName = 'short';
console.log(date.toLocaleDateString('en-US'), date.toLocaleTimeString('en-US', options));

Related

Creating timezone independent dates in Javascript?

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

How to obtain a local timezone Date from a date string in javascript?

I am building an online store, most of my customers (basically all) are located in a given timezone, but my infrastructure is located in other timezone (we can assume it's UTC). I have the option for my clients to select a date for their orders, the problem is that my date component represents dates like this "YYYY-MM-DD". In am using the Date constructor like this:
let dateString = "2019-06-03"
let date = new Date(dateString)
console.log(date) //This will print the local time zone representation of my dateString
console.log(date.toISOString()) //This will print the utc equivalent of my dateString
The problem with this is that I want the UTC representation to be calculated from the local timezone, not the other way around. Let's suppose in am located in GMT-5, when I say let date = new Date("2019-06-06") I want to see "2019-06-03T00:00:00.000 GMT-5" , and the ISOString should be "2019-06-03T05:00:00.000Z". How can I do this ?
What you are trying to achieve can be done by appending the string T00:00:00 to the dateString before passing it to the Date() constructor.
But a word of caution, manipulating the timezone/offsets manually like this might result in incorrect data being presented.
If you are storing and retrieving all the order timestamps in UTC only, it will avoid timezone related issues and you might not need to process the timestamps like this.
let dateString = "2019-06-03"
let date = new Date(dateString + "T00:00:00")
console.log(date) //This will print the local time zone representation of my dateString
console.log(date.toISOString()) //This will print the utc equivalent of my dateString

Converting date from string with offset to different timezone

I'm wondering on the correct way to convert a string date in a non-ISO format to a different offset/timezone.
I am currently given 3 values:
the date in format MM/DD/YYYY (23/11/2016)
the time in 24h format (23:13)
timezone offset (-07:00)
I would like to convert said date to the user's timezone.
I am trying to convert the format to the format accepted by moment timezone's moment.tz() function ('2016-11-23T23:13-07:00') but I am not sure how to do that without splitting the date array and converting it to said date.
Moment's timezone has the tools I need to convert the date afterwards to the local timezone. For example:
moment.tz('2016-11-23T23:13-07:00', moment.tz.guess());
Any thoughts on how to convert 23/11/2016 23:13 with offset -07:00 to the local date preferably using momentJS?
Why not just format as an ISO 8601 string with offset and give that to moment.js?
function customToISOString(date, time, offset){
return date.split(/\D/).reverse().join('-') + 'T' + time + offset;
}
document.write(customToISOString('23/11/2016','23:13','-07:00')); // 2016-11-23T23:13-07:00
Most modern browsers will also parse that, but don't do it as there are still plenty of older browsers around where it will fail.
I like Rob's answer, but I'll also give you it in moment.js.
First, you don't need moment-timezone, and you definitely don't need to guess the time zone id just to convert to that zone. In ISO format, it would just be like this:
var m = moment('2016-11-23T23:13-07:00');
This will read in the offset during parsing, apply it, then convert to the local time zone, returning a moment object in "local mode". This is the default mode, so it just works.
With the requirements you described it would be like this:
// your inputs
var d = "23/11/2016";
var t = "23:13";
var o = "-07:00";
var m = moment(d + ' ' + t + o, 'MM/DD/YYYY HH:mmZ');
Note that I add the space between the date and time just for safety, so there's no risk of mixing the year and the hour components.
Again it will automatically apply the offset and convert to the local time zone, since that's the default behavior. If you want some other behavior, there are ways to do that as well.

Using momentjs to convert date to epoch then back to date

I'm trying to convert a date string to epoch, then epoch back to the date string to verify that I'm providing the correct date string.
var epoch = moment("10/15/2014 9:00").unix(); // do I need to do .local()?
var momentDate = moment(epoch); // I've also tried moment.utc(epoch)
var momentDateStr = momentDate.calendar();
alert("Values are: epoch = " + epoch + ", momentDateStr = " + momentDateStr);
Renders
Values are: epoch = 1413378000, momentDateStr = 01/17/1970
Note: I'm using the following version of the moment js script, //cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment-with-locales.js
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local() or .utc().
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
http://momentjs.com/docs/#/displaying/unix-timestamp/
You get the number of unix seconds, not milliseconds!
You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.
moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

How to assume local time zone when parsing ISO 8601 date string?

I have a ISO date string as below
var startTimeISOString = "2013-03-10T02:00:00Z";
when I convert it to date object in javascript using below code, it returns
var startTimeDate = new Date(startTimeISOString);
output is
Date {Sun Mar 10 2013 07:30:00 GMT+0530 (India Standard Time)}
It sure converts the ISOString to date but it converts to local time since new Date() is client dependent. How to just convert iso date time string to date and time but not to local date-time..?
Thanks
According to MDN:
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time
zone, but given an ISO format such as "2014-03-07" it will assume a
time zone of UTC. Therefore Date objects produced using those strings
will represent different moments in time unless the system is set with
a local time zone of UTC. This means that two date strings that appear
equivalent may result in two different values depending on the format
of the string that is being converted (this behavior is changed in
ECMAScript ed 6 so that both will be treated as local).
I have done like this and am now getting the exact time which is inside the ISO date string instead of the local time
var startTimeISOString = "2013-03-10T02:00:00Z";
var startTime = new Date(startTimeISOString );
startTime = new Date( startTime.getTime() + ( startTime.getTimezoneOffset() * 60000 ) );
This will give the same date time inside iso date string , the output here is
o/p
Date {Sun Mar 10 2013 02:00:00 GMT+0530 (India Standard Time)}
To sum up the conversation from tracevipin's post:
All Date objects are based on a time value that is milliseconds since 1970-01-01T00:00:00Z so they are UTC at their core. This is different to UNIX, which uses a value that is represents seconds since the same epoch.
The Date.prototype.toString method returns an implementation dependent string that represents the time based on the system settings and timezone offset of the client (aka local time).
If a UTC ISO8601 time string is required, the Date.prototype.toISOString method can be used. It's quite easy to write a "shim" for this methods if required.
Lastly, do not trust Date.parse to parse a string. Support for an ISO8601 format UTC string is specified in ES5, however it's not consistently implemented across browsers in use. It is much better to parse the string manually (it's not hard, there are examples on SO of how to do it) if wide browser support is required (e.g. typical web application).
Simple ISO8601 UTC time stamp parser:
function dateObjectFromUTC(s) {
s = s.split(/\D/);
return new Date(Date.UTC(+s[0], --s[1], +s[2], +s[3], +s[4], +s[5], 0));
}
and here's a shim for toISOString:
if (typeof Date.prototype.toISOString != 'function') {
Date.prototype.toISOString = (function() {
function z(n){return (n<10? '0' : '') + n;}
function p(n){
n = n < 10? z(n) : n;
return n < 100? z(n) : n;
}
return function() {
return this.getUTCFullYear() + '-' +
z(this.getUTCMonth() + 1) + '-' +
z(this.getUTCDate()) + 'T' +
z(this.getUTCHours()) + ':' +
z(this.getUTCMinutes()) + ':' +
z(this.getUTCSeconds()) + '.' +
p(this.getUTCMilliseconds()) + 'Z';
}
}());
}
This happens because date is printed using toString method which by default returns the date and time in local timezone. The method toUTCString will give you the string you need.
Date actually keeps the date as unix time in milliseconds and provides methods to manipulate it.
In vanilla javascript there isn't a way to create a date that assumes the local time of the ISO formatted string you give it. Here's what happens when you pass an ISO 8601 formatted string to javascript. I'm going to use a non UTC time as it illustrates the problem better than using an ISO formatted string:
var startTime = new Date("2013-03-10T02:00:00+06:00"). Note this could also be 2013-03-10T02:00:00Z or any other ISO-formatted string.
read the time, apply the offset and calculate milliseconds since 1970-01-01T00:00:00Z
You now have only milliseconds - you have lost all timezone info. In this case 1362859200000
All functions, apart from the ones that give you a UTC representation of that number, will use the timezone of the computer running the code to interpret that number as a time.
To do what the original poster wants, you need to.
parse the ISO string, interpret the offset ('Z' or '+06:00') as the timezone offset
store the timezone offset
calculate and store the ms since epoch, using the offset timezone offset
hold that offset
whenever attempting to make a calculation or print the date, apply the timezone offset.
This isn't trivial, and requires a complete interpretation of the 8601 spec. Way too much code to put here.
This is exactly what moment.js is designed to do. I strongly recommend using it. Using moment.js:
moment("2013-03-10T02:00:00Z").format()
"2013-03-10T02:00:00Z"
this will result in printing the ISO time of the original string, preserving the offset.
you can try moment js library https://momentjs.com
For my case, I had 2022-10-17T01:00:00 on my database. SO I need to format it to the 01:00:00 AM.
So here was my solution.
var date = "2022-10-17T01:00:00"
var timeFormat = moment(date ).format('HH:mm A');
output: 01:00:00 AM
it will return ISOdate
var getDate = () => {
var dt = new Date();
var off = dt.getTimezoneOffset() * 60000
var newdt = new Date(dt - off).toISOString()
return newdt.slice(0, 19)
}
Output

Categories