UTC iso8601 date to certain format with local timezone - javascript

I have the UTC date in this format: 2015-12-09T15:44:33.737
Currently I am doing
var ts = '2015-12-09T15:44:33.737'
var localTimeString = new Date(ts).toLocaleDateString() + ", " + new Date(ts).toTimeString();
See here: http://jsbin.com/pakoxegete/1/edit?js,console
to get 12/9/2015, 10:44:33 GMT-0500 (Eastern Standard Time)
But the format I would like is
12/09/2015, 10:44:33 AM EST
The main changes I am after is ability to go from military time to standard time with AM/PM and also to be able to convert GMT-0500 (Eastern Standard Time) to EST. The time zones only have to work for the main timezones located in the USA.
Edit: I am interested in PST, MST, CST, EST and their daytime counter parts: PDT, MDT, CDT, EDT

I guess the functions has more options that I expected. Was able to compromise and get this
var ts = '2015-12-09T15:44:33.737'
var options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', timeZoneName: 'short' };
console.log(new Date(ts).toLocaleDateString('en-US', options));
Which results in December 9, 2015, 10:44 AM EST

Related

Format date in JS, and keep the date format for different locales

I have a setting for a date format that looks like:
const shortMonth12 = {
year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: 'true' };
Which will give me the following date format:
console.log(date.toLocaleString('en-US', shortMonth12)) // "Mar 28, 2022, 01:55 PM"
Great, it works and we have the date format we want. We dont want to change it.
But we also want to also translate the month name. But problem is the format itself also changes when providing another locale. For example:
console.log(date.toLocaleString('sv-SE', shortMonth12)); // "28 mars 2022 01:55 em"
So, we want to use the locales to translate the months, but also keep the formatting the same. Is it possible the way the implementation looks like?
So, we want to use the locales to translate the months, but also keep the formatting the same.
No, since toLocaleString uses the provided locale to format the date, the outcome is depending on the locale.
If you use 2 different locale's that have different date formats, like en-US and sv-SE you'll get different formats, as intended.
en-US: Mar 28, 2022, 02:19 PM
sv-SE: 28 mars 2022 02:19 em
You can get the desired outcome by creating the string manual, this requires some more logic and goes against the idea behind toLocaleString.
Use the functions like toLocaleTimeString and getFullYear to create variables based on the locale, then create a string with the desired format, for example:
const customFormat = (date, locale) => {
let d = date.getDate(),
m = date.toLocaleString(locale, { month: 'long' }),
y = date.getFullYear(),
t = date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: 'true' });
return `${d} ${m}, ${y}, ${t}`;
}
const d = new Date();
const d1 = customFormat(d, 'en-US');
const d2 = customFormat(d, 'sv-SE');
console.log(d1); // 28 March, 2022, 02:25 PM
console.log(d2); // 28 mars, 2022, 02:25 em

Format JS date.toLocaleString differently

var date = new Date();
date.setDate(date.getDate() + 1)
console.log(`streak=0; expires=${date.toLocaleString('en-us', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}`);
In my output, I get
streak=0; expires=Sunday, January 2, 2022
My question is:
How can I format the date like this:
Thu, 18 Dec 2013 12:00:00 UTC
(12 and UTC don't need to be included)
I want the date number to go first then the month, not the other way around.
I am doing this because I need it to be formatted like that for a cookie:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
(w3schools)
Tell me if that's not how you use cookies.

Convert a date with GMT to a human readable time zone in an angular app using TS or JS

I have a date value returned from an api call. This date includes a value like GMT-7. How best to turn that into a human readable time zone like 'PST' or 'Pacific Standard Time' so final string will be December 31, 2021 at 4:00:00 PM (PST) and not GMT-7
The GMT/UTC minus 7 hours offset is used in the Pacific Time Zone during Daylight Saving Time (DST) period and in the Mountain Time Zone during the Standard Time period, when no DST is applied.
Moment.js is not an option because of it's file size and deprecation.
Ok further clarification from my product owner: the time can be returned reflecting the time in the users time zone. So if it is 7pm EST time in the original date and user is in Pacific Time PST they will see 3pm PST to reflect same time according to their zone.
There is no standard for timezone names or abbreviations, and sometimes with either timeZoneName short or long the format* methods will return something like GMT+07:00 or UTC+07:00 depending on the browser default language, even if "en" or "en-US" or whatever is specified.
However, you can use Intl.DateTimeFormat with formatToParts and timeZoneName:'long' then abbreviate it yourself where the timeZoneName value doesn't contain numbers.
This won't fix cases where the implementation doesn't have a name for the timezone, but for more common timezones like those in Europe and the US with language "en" it should be OK, e.g.
function formatDate(date) {
let {year, month, day, hour, minute, second, timeZoneName} = new Intl.DateTimeFormat("en", {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: 'America/Los_Angeles',
timeZoneName:'long'
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
// If timezone doesn't contain numbers, abbreviate
// Otherwise, return the name as given by formatToParts
let tz = /\d/.test(timeZoneName)? timeZoneName : timeZoneName.replace(/[^A-Z]/g,'');
return `${month} ${day}, ${year} ${hour}:${minute}:${second} ${tz}`
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(2021,0,1)));
console.log(formatDate(new Date(2021,5,1)));
You may try to use new Date().toLocaleString(......) function.
let date = api date
new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()))
converts to gmt 00:00

Convert UTC time to Browser's local time in angularjs/javascript

From the server I am getting a DateTime in this format: 2019-07-11T05:33:53.45 and it is in UTC time.
I want to convert it to the current user’s browser time using JavaScript in the format like 11th July 2019 11:03 AM which is UTC+0530 for Indian time for given time(2019-07-11T05:33:53.45).
I have tried Intl.DateTimeFormat and also other JavaScript date time functions eg. toLocaleString. But I am getting the time in UTC format only. When I get the time as what I want UTC+0530 is also attached, which I don't want.
let d = new Date(date_from_server);
let options= { year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false };
let ddmmmyy= new Intl.DateTimeFormat('default', options).format(d);
This is one of the solution I tried. I have tried other methods also, but didn't succeed.
eg. let ddmmmyy = d.toLocaleString();
I want the time as per User's current browser timezone and in the specified format(11th July 2019 11:03 AM IST).
How can I achieve it? Please help.
You need to replace the T in the date string and also append UTC.
Then you need to remove GMT and anything after that in the result:
var dateString = "2019-07-11T05:33:53.45".replace('T', ' ') + " UTC"; // or + "Z" instead of + " UTC";
var dateObj = new Date(dateString);
var localDateString = dateObj.toString().replace(/GMT.*/g,"");
console.log(localDateString);
Try this:
var date = new Date('2019-08-14 17:00:34 UTC');
date.toString(); // outputs "Wed Aug 14 2019 13:00:34 GMT-0400 (Eastern Daylight Time)"

Intl.DateTimeFormat gives strange result from year 1847 or below

Why is it that if I choose a year below 1848, the result of this format is May 10?
I have a feeling this could be about time zones? If so how can I avoid this, given that I will be creating a date object from an ISO date string (without time) like this: YYYY-MM-DD.
(Tested on Chrome 59)
const workingDate = Intl.DateTimeFormat('en-GB').format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)'));
const notWorkingDate = Intl.DateTimeFormat('en-GB').format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)'));
console.log(workingDate);
console.log(notWorkingDate);
Date strings above are from e.g. new Date('1847-05-11') (I'm in BST time zone)
This test was made in Chrome 53.
I've added some options to DateTimeFormat to check the other fields of the date:
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false, timeZoneName: 'long'
};
var workingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)'));
var notWorkingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)'));
The result was:
workingDate: 10/05/1848, 20:53:32 GMT-03:06:28
notWorkingDate: 10/05/1847, 20:53:32 GMT-03:06:28
Most places didn't have standardized UTC-based offsets before 1900 (actually, each country adopted it in a different year), so before 1900 you always get those strange results. Actually, as Matt explained in the comments, UTC was implemented in 1972 and before that most zones were defined as offsets from GMT. Anyway, for very ancient dates, specially before 1900, you might expect offsets like the above.
In this case, it's getting the corresponding offset for my system's default timezone (America/Sao_Paulo): before 1914 it was -03:06:28.
In London (which I'm assuming it's your default timezone), before 1847-12-01 the offset was -00:01:15 (calculated by lat/lon, see again Matt's comment for more details), and after that it was changed to +00:00 (that' why it works for dates in 1848).
I've made a test setting the timezone to Europe/London:
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false, timeZoneName: 'long', timeZone: 'Europe/London'
};
var workingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)'));
var notWorkingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)'));
The result was:
11/05/1848, 00:00:00 GMT
10/05/1847, 23:58:45 GMT-00:01:15
Which confirms that before December/1847, dates had a different offset.
One way to fix it, is to consider the date as UTC:
options = {
timeZone: 'UTC'
};
var workingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1848 01:00:00 GMT+0100 (BST)'));
var notWorkingDate = Intl.DateTimeFormat('en-GB', options).format(new Date('Fri May 11 1847 01:00:00 GMT+0100 (BST)'));
The values will be:
11/05/1848
11/05/1847

Categories