Formatting a predefined Date value to ISO format in JavaScript - javascript

I need to send a date value to the server in ISO Format "YYYY-MM-DDTHH:mm:ss.SSS[Z]" I don't need the time details so I am setting them as zero.
For that I am using the below code
var today = new Date();
var todayWithTimeAsZero = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
I get todayWithTimeAsZero as Tue Jul 25 2017 22:06:03 GMT+0530 (India Standard Time)
Now how do I convert this date into an ISO format. I researched everywhere but no luck.
I tried var day = todayWithTimeAsZero.toISOString(); but this creates a new date object with the time values populated like so 2017-07-24T18:30:00.000Z. Also I have momentjs in my project may be in some way I can use that.

With moment.js you can get the current date as UTC, then set the time values to zero and get the ISO string:
moment() // current date
.utc() // convert to UTC
.hours(0).minutes(0).seconds(0).milliseconds(0) // set time values to zero
.toISOString() // format to ISO8601
The value of the formatted string is 2017-07-25T00:00:00.000Z.
You can also use the setUTCxxx methods of Date:
var today = new Date();
today.setUTCHours(0);
today.setUTCMinutes(0);
today.setUTCSeconds(0);
today.setUTCMilliseconds(0);
today.toISOString() will be 2017-07-25T00:00:00.000Z.

If you create a Date then zero the UTC time and get just the date, it will be a different date from the local date for the period of the timezone offset. For someone in UTC+1000 the UTC date is yesterday until 10:00. For users who are UTC-0600 it will be "tomorrow" after 18:00 (6 pm).
Anyway, without any library you can do:
var d = new Date();
d.setUTCHours(0,0,0,0);
console.log(d.toISOString());

Related

Get Date Object with UTC instead of local time zone in vanilla javascript

I am uploading a date time to a field on a dynamics form, and the form needs to receive a UTC date time. If I do something like this:
new Date(new Date().toISOString())
If i console.log the date it shows as: Fri Dec 18 2020 14:27:39 GMT-0500 (Eastern Standard Time)
I want the object to print as the UTC time with UTC specified as the time zone, otherwise the form (expecting a date object) keeps uploading as the EST time.
Use Date.UTC
const utcDate1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
Docs
Edit: As another user mentioned, you must use Date.UTC.
var date = new Date(Date())
var utcDate = date.toUTCString();
console.log(utcDate)
Date objects are just an offset in milliseconds from the ECMAScript epoch, 1970-01-01T00:00:00Z. They do not have a timezone. When you stringify the object you get a timestamp that depends on the method used.
Most methods (e.g. toString) use the host settings for timezone and offset and produce timestamps based on those settings.
If you want an ISO 8601 compliant string with zero offset, the use toISOString or toUTCString depending on the format you want:
let d = new Date();
console.log(`local time : ${d.toString()}`);
console.log(`toISOString: ${d.toISOString()}`);
console.log(`toUTCString: ${d.toUTCString()}`);
See How to format a JavaScript date.
In your code, the expression:
new Date(new Date().toISOString())
firstly creates a Date object for the current moment in time, then generates a timestamp per the toISOString method. That is then parsed back into a Date object, so the result is identical to:
new Date();

How to convert dates with 3 letter timezone abbreviation, to UTC, in Javascript?

I need to convert datetimes from an input format which I can't change (this: "Tue, 30 Jul 2019 21:15:53 GMT") to UTC, in Javascript.
I actually need to get these dates as the number of milliseconds since the Unix epoch (1970) but getting in UTC would be a start.
Is there a way to do this easily? I can use a 3rd party library if needed. I've heard of moment-timezone.js but not clear how to parse the 3 letter timezone, i.e. these: https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations.
The correct solution is a library that maps these abbreviations to offsets from GMT. Neither moment-timezone, nor date-fns-tz, nor luxon, nor timezone-support do this, but timezone-abbr-offsets does and is very minimalistic.
Fortunately, new Date() can parse your format minus the timezone, so we'll split that away and calculate the offset back:
import timezones from 'timezone-abbr-offsets';
function abbrTzToUtc(dateString) {
// Get the date and the timezone from the input string
let [, date, tz] = dateString.match(/^(.*)\s+(\w+)$/);
// Ignore the timezone and parse the date as GMT
date = new Date(date + 'Z');
// Add the offset caused by the original timezone
date = new Date(date.getTime() + timezones[tz] * 60 * 1000);
return date;
}
console.log(abbrTzToUtc('Tue, 30 Jul 2019 21:15:53 MET'));
As a test, the code above should return 2019-07-30T22:15:53.000Z.
If you want number of milliseconds since the Unix epoch, return date.getTime() instead.
If you want to convert the date into UTC format you can use toISOString()
new Date('Tue, 30 Jul 2019 21:15:53 GMT').toISOString()
For more info please check this reference
Moreover, to convert the date into milliseconds you can use Date.UTC()
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])
reference
Example:
utcMillisecond = (e) => {
const regex = /(T)|(:)|(-)/g;
const utc = new Date(e).toISOString().slice(0, 19).replace(regex, ' ').split(' ');
const utcMillisecond = Date.UTC(utc[0], utc[1], utc[2], utc[3], utc[4])
return utcMillisecond
}
utcMillisecond("Tue, 30 Jul 2019 21:15:53 GMT")
//1567199700000

Convert string to Date without considering timezone - Typescript

I'm getting a date as a string, in the following format (for example):
"11/10/2015 10:00:00"
This is UTC time.
When I create Date from this string, it consider it as local time:
let time = "11/10/2015 10:00:00";
let date = new Date(time);
console.log(date);
it prints:
"Tue Nov 10 2015 10:00:00 GMT+0200"
(instead of considering it as UTC: "Tue Nov 10 2015 10:00:00")
I also tried moment.js for that.
is there a good way to make Date() consider the string a UTC, without adding "Z"/"UTC"/"+000" in the end of the string?
You can use the built-in Date.UTC() function to do this. Here's a little function that will take the format you gave in your original post and converts it to a UTC date string
let time = "11/10/2015 10:00:00";
function getUTCDate(dateString) {
// dateString format will be "MM/DD/YYYY HH:mm:ss"
var [date, time] = dateString.split(" ");
var [month, day, year] = date.split("/");
var [hours, minutes, seconds] = time.split(":");
// month is 0 indexed in Date operations, subtract 1 when converting string to Date object
return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)).toUTCString();
}
console.log(getUTCDate(time));
Your date is parsed by the date constructor, in MM/DD/YYYY format, applying the local timezone offset (so the output represents local midnight at the start of the day in question). If your date really is MM/DD/YYYY, all you need to do is subtract the timezone offset and you'll have the UTC date...
var myDate = new Date("11/10/2015 10:00:00");
myDate = new Date( myDate.getTime() - (myDate.getTimezoneOffset()*60*1000));
console.log(myDate.toLocaleString([],{timeZone:'UTC'}))
Here's everything I know about managing timezone when serializing and deserializing dates. All the timezone handling is static! JS dates have no intrinsic timezone.
You can use Date.UTC for this but you will have to parse your string and put every part of it as args by yourself as it can't parse such string. Also you could use moment.js to parse it: Convert date to another timezone in JavaScript
Also, seems like new Date("11/10/2015 10:00:00 GMT") parses date as a GMT and only after that converts it to PC local time
Easy answer is to append a "Z" at the end without changing the variable:
let time = "11/10/2015 10:00:00";
let date = new Date(time + "Z");
console.log(date);

Time zone issue involving date fns format()

const dt = new Date('2017-12-12');
console.log(format(dt, 'YYYY-MM-DD'));
The above code logs 2017-12-11 in the US, but 2017-12-12 in India.
I followed this github thread here and tried out things but am not getting the desired results.
My expectation is to print the same date irrespective of time zone
Why I need this :
Consider a scenario involving birthdates. If i am giving some input date, it has to be displayed as same date in all regions irrespective of their timezones.
You will need to subtract the time zone offset of your local time zone from the Date instance, before you pass it to format from date-fns. For example:
const dt = new Date('2017-12-12');
const dtDateOnly = new Date(dt.valueOf() + dt.getTimezoneOffset() * 60 * 1000);
console.log(format(dtDateOnly, 'YYYY-MM-DD')); // Always "2017-12-12"
Problem
You want to handle only the date part of the Date instance, because the time part does not make sense for birthdates. However, the Date object does not offer any "date-only" mode. You can access both its date and time parts in the local time zone or UTC. The problem is, that format from date-fns prints the output always in the local time zone.
When you executed the constructor only with the date part:
const dt = new Date('2017-12-12');
The JavaScript engine actually assumed a string in the incomplete ISO 8601 format and perfomed this:
const dt = new Date('2017-12-12T00:00:00.000Z');
It may still look "harmless" to you, but the date instance exposes the value not only in UTC, but also in the local time zone. If you construct the Date instance on the East Coast of the US, you will see the following output:
> const dt = new Date('2017-12-12');
> dt.toISOString()
'2017-12-12T00:00:00.000Z'
> dt.toString()
'Tue Dec 11 2017 19:00:00 GMT-0500 (EST)'
> d.toLocaleString()
'12/11/2017 7:00:00 PM'
Solution
If you know, that format from date-fns reads date and time parts from the date instance in the local time zone, you will need to make your date "looking like" the midnight in your local time zone and not in UTC, which you passed to the Date constructor. Then you will see the year, month and date numbers preserved. It means, that you need to subtract the time zone offset of your local time zone for the specified day. Date.prototype.getTimezoneOffset returns the offset, but with an inverted sign and in minutes.
const dt = new Date('2017-12-12');
// Tue Dec 11 2017 19:00:00 GMT-0500 (EST)
const dtDateOnly = new Date(dt.valueOf() + dt.getTimezoneOffset() * 60 * 1000);
// Tue Dec 12 2017 00:00:00 GMT-0500 (EST)
console.log(format(dtDateOnly, 'YYYY-MM-DD'));
// Prints always "2017-12-12", regardless the time zone it executed in
However, such Date instance can be used only to format the date-only value. You cannot use it for computing date differences, for example, which would need the original and correct UTC value.
Alternative
If you need always the same date-only format and not the format specific to the current locale, you do not need date-fns. You can format the string by the concatenation of padded numbers:
const dt = new Date('2017-12-12');
const year = dt.getUTCFullYear()
const month = dt.getUTCMonth() + 1 // Date provides month index; not month number
const day = dt.getUTCDate()
// Print always "2017-12-12", regardless the time zone it executed in
console.log(year + '-' + padToTwo(month) + '-', padToTwo(day));
// Or use a template literal
console.log(`${year}-${padToTwo(month)}-${padToTwo(day)}`);
function padToTwo (number) {
return number > 9 ? number : '0' + number
}
Only adding the #ferdinand-prantl answer. If you are using the date-fns, you can parse the string date ('2017-12-12') using the parseISO(here) fn from date-fns, which will complete the missing ISO 8601 format with your local time zone. When you use the format fn, you are going to keep the date.
const strDate = '2017-12-12';
const isoDate = parseISO(strDate);
const formattedDate = format(isoDate, 'YYYY-MM-DD');
console.log({strDate, isoDate, formattedDate})
//{
// strDate: '2017-12-12',
// isoDate: 2017-12-12T02:00:00.000Z,
// formattedDate: '2017-12-12'
//}

JS get date in UTC time

I've created a date in JS like so:
var myDate = new Date('2013-01-01 00:00:00');
I assume JS reads this in as UTC time. But when I do something like myDate.getTime() the timestamp returned was something like 4AM GMT time.
Why is this? And how do I get the date as midnight in UTC time?
At least in Chrome, this works:
var myDate = new Date('2013-01-01 00:00:00 UTC');
It also works if you put GMT instead of UTC. But I don't know if this is cross-browser enough.
I live in India. Hence my timezone is the Indian Standard Time (IST) which is listed in the tz database as Asia/Kolkata. India is 5 hours 30 minutes ahead of GMT. Hence when I execute new Date("2013-01-01 00:00:00") the actual time at GMT is "2012-12-31 18:30:00".
I believe you live in America because you're in the EST timezone (GMT-04:00)? Am I right?
If you want to parse the time at GMT instead of your local timezone then do this:
new Date("2013-01-01T00:00:00+00:00");
Notice the capital T between the date and the time, and the +00:00 at the end. This is the format used to parse a given time in a specific timezone.
Given the date string "2013-01-01 00:00:00" you can convert it to the required format using the following function:
function formatDateString(string, timezone) {
return string.replace(" ", "T") + timezone;
}
Then you can create the date as follows:
new Date(formatDateString("2013-01-01 00:00:00", "+00:00"));
Another way to convert local time to GMT is as follows:
var timezone = new Date("1970-01-01 00:00:00"); // this is the start of unix time
Now that you have your own local timezone as a date object you can do:
new Date(new Date("2013-01-01 00:00:00") - timezone);
All the above methods produce the same date at GMT.
JS reads this with time zone that your computer uses.
You can try use myDate.toUTCString() for get date in UTC time.
If you want get timestamp use myDate.getTime()
Mine works simply by doing this
var datetime= new Date()
However the month is 1 low so you have to add one

Categories

Resources