How to get date in specific locale with JavaScript? - javascript

I need to get the date in a specific locale using JavaScript - not necessarily the user's locale. How can I do this?
I did some research and found date.getUTCMonth() and date.getUTCDate(). How can I use this or something else to get the date in a certain locale?

You can use toLocaleDateString:
From the MDN documentation:
The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
const event = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));

Related

How to add specific characters in between values of a JavaScript date?

I am trying to format a date in JavaScript to fit a specific format.
My desired format is 29-Jan-2021
With the below code I have managed to generate "29 Jan 2021":
var newDate = new Date('2021-01-29T12:18:48.6588096Z')
const options = {
year: 'numeric',
month: 'short',
day: 'numeric',
};
console.log(newDate.toLocaleString('en-UK', options))
Can someone please show me how I can add - between the day, month, & year in the date above?
Well you if you have already able to find the string close to your answer you can achieve your solution with either of the two methods.
Either you can use replaceAll() or replace(). Both will be able to solve the issue.
let dateFormat = "29 Jan 2021"
console.log(dateFormat.replaceAll(" ","-")) // 29-Jan-2021
console.log(dateFormat.replace(/ /g,"-")) // 29-Jan-2021
Well I would suggest you to use replace() over replaceAll as some browsers do not support replaceAll(). Do check replaceAll support.

Formatted JavaScript Date is one day behind [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
I have a date: yyyy-mm-dd that I am formatting using the International DateTimeFormat like this:
const formatter = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric', timeZone:'America/Denver'});
// GiVES SAME RESULTS AS ABOVE
//const formatter = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric'});
//const formatter = new Intl.DateTimeFormat("default" , { month: '2-digit', day: '2-digit', year: 'numeric'});
let date = "2020-03-19"
return formatter.format(Date.parse(date));
//returns 03/18/2020 which is one day behind
I've tried this with and without the timeZone attribute. How can I fix this?
The ECMAScript Date Time String Format defines formats for both date-time forms as well as date-only forms. These are used by the Date.parse function and the Date constructor when a string is passed. Behavior for those functions is defined in the docs for the Date.parse function, which contain the following statement:
... 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.
Thus, when you call Date.parse('2020-03-19') the defined behavior is to treat that as UTC, not as local time. (This deviates from ISO 8601.)
To change this behavior, append a time string or a time+offset string.
For example, if you want to parse the time in the local computer's time zone:
Date.parse('2020-03-19T00:00:00.000')
Or, if you want to parse in a particular time zone and know the correct offset for the given timestamp in that time zone:
Date.parse('2020-03-19T00:00:00.000-05:00')
Often one doesn't know the offset, but does know the IANA time zone identifiers (such as 'America/Chicago'). Unfortunately, ECMAScript doesn't currently have the capability to parse in a named time zone yet. That capability will be possible if/when the TC39 Temporal proposal is adopted. Until then, you could use a library such as Luxon to perform such an action. For example:
luxon.DateTime.fromISO('2020-03-19', { zone: 'America/Chicago' }).toString()
//=> "2020-03-19T00:00:00.000-05:00"
Date.parse("2020-03-19") indicates 2020-03-19 00:00:00 GMT, so it will be 2020-03-18 for America/Denver, which will be 2020-03-18 17:00:00 America/Denver
const formatter1 = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric', timeZone:'America/Denver'});
const formatter2 = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric'});
let date = "2020-03-19"
console.log(formatter1.format(Date.parse(date)));
console.log(formatter2.format(Date.parse(date)));
You have added time zone, because of that it convert date into that time zone and because of the zone it can be 1 day behind or next day.

How to convert from date.now to pacific time

On my current project, I have to implement elapsed time for each user and display it on the webpage.
However, using the date.now will return utc and I would like to get it in pacific time. I googled and researched through online but could not get it to work... Is there a way to convert from utc to pacific time?
You can do something like this:
const event = new Date(Date.now());
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('us-PT', options));
Where "us" is the "United States" and "PT" is "Pacific-Time"
To see more go to MDN web docs Date.prototype.toLocaleDateString()
I see a few options you have at hand.
Option 1 - use an external library (moment / date-fns)
Consider using these libraries if your app is going to heavily rely on timezones, dates etc.
For example:
moment.tz(12345678, "America/Los_Angeles") // 12345678 being your Date timestamp
See more info here:
date-fns
moment
Option 2 - you need to use vanilla JS
Found a few answers on this thread, but I couldn't see any of them being long term reliable (because of savings time etc.) - I might be wrong about it, but I resort to date/time libraries when my app heavily uses the same.
This worked for me.
const date = new Date().toLocaleDateString('en-US', { timeZone: 'America/Los_Angeles' });
const time = new Date().toLocaleTimeString('en-US', { timeZone: 'America/Los_Angeles' });
const datetime = new Date().toLocaleString('en-US', { timeZone: 'America/Los_Angeles' });
Hope it helps others save time.

Any javascript library which can parse string created by Intl.DateTimeFormat?

Is there any javascript library which can parse string created by Intl.DateTimeFormat and give a Date?
For example:
options = {
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
weekday: "short",
}
var test_date = new Date();
console.log(new Intl.DateTimeFormat('hr', options).format(test_date));
// note that test_date is just an example.
// We need to parse text created Intl.DateTimeFormat and give a Date.
will return:
sub, 21. ožu 2020. 12:41
That is great - exactly how it should be written.
But how to parse it back to be a Date?
Something like:
Date.parse('sub, 21. ožu 2020. 12:41', options, 'hr')
// hr is locale
// options are same a options given to Intl.DateTimeFormat
We tried momentjs and format 'llll', but sadly momentjs locale are different that Intl.DateTimeFormat implementation on Google Chrome (i.e., dots are added in wrong places, abbreviations for dates are incorrect, etc.). We tested with 'hr', 'sk', and few others and no luck :(
So is there any library which any javascript library which can parse string created by Intl.DateTimeFormat?

Javascript How to convert a timezone into the actual timezone abbreviation?

I have a date and need to convert it into this format
02/27/2020 3:00PM (MST)
What is the fastest way to do that in javscript like a one liner?
I tried
var options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'short' };
this.date = new Date().toLocaleDateString("en-US", options);
This also does not work
new Date().toLocaleDateString(Intl.DateTimeFormat().resolvedOptions().timeZone, options);
as I am getting asia/caluctta invalid language tag
While this works for UnitedStates this does not work for users in russia, india, europe, china.
It will show the date as
02/28/2020 +500 GMT
I need it to show as
02/28/2020 (IST) for India
or
02/28/2020 (JST) for Japan Standard time
I can recommend you to try Moment.js. It's a javascript library made especially for easier manipulation with time. Just download the .js and add it to your index.html before your script.

Categories