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?
Related
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.
How can i convert this 2021-01-10 12:47:29 UTC to January 10, 2021?
I'm using this below using moment.js but this works browsers but not in Safari
{moment(video?.createdAt).format('MMMM D, YYYY')}
Moment.js is deprecated. Here's an alternative using native JS features.
First we need to convert the date string into a Date object. Calling new Date(video?.createdAt) is not reliable as mentioned on the Date() constructor page on MDN:
Parsing of date strings with the Date constructor
(and Date.parse(), which works the same way)
is strongly discouraged due to browser differences and inconsistencies.
See Date Time String Format on MDN for reference of the correct format. For example:
// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
const [date, time] = dateString.split(' ')
return new Date(`${date}T${time}.000Z`) // Z = UTC
}
Then we can use Date.prototype.toLocaleString() to format the Date object:
// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
const [date, time] = dateString.split(' ')
return new Date(`${date}T${time}.000Z`) // Z = UTC
}
function format(dateString) {
if (!dateString) return 'some fallback value'
const date = parseDate(dateString)
return date.toLocaleString('en', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
}
console.log(format('2021-01-10 12:47:29 UTC'))
//=> January 10, 2021, 2:47 PM
console.log(format(undefined))
//=> some fallback value
See Intl.DateTimeFormat() for all possible options. For example, these options produce slightly different results:
return date.toLocaleString('en', {
dateStyle: 'long',
timeStyle: 'short',
})
format('2021-01-10 12:47:29 UTC')
//=> January 10, 2021 at 2:47 PM
If the date strings can be in various formats, you probably need more robust date parsing. Or if you need exotic formattings, toLocaleString() might not meet your needs. In those cases, it might be useful to use one of the recommended Moment.js alternatives.
The new Intl DateTimeFormat API is gaining more support natively in many browsers, so it is a more future proof solution. As suggested in the doc, you can use polyfills for browsers which lack full support of this feature. Unfortunately, Safari is one of the browser which is yet to catch up.
A short snippet to achieve what you are looking for would be
new Intl.DateTimeFormat('en-US', { dateStyle: 'long'}).format(new Date("2021-01-10 12:47:29Z")) // outputs January 10, 2021
Keep in mind that date time string without Z at the end would be parsed as local time. Z means the date time supplied is UTC.
If you're searching for moment.js alternative, I would suggest date-fns. Here is a blog post that compares the 2 of them.
Here is the format documentation for date-fns.
So to answer your question using date-fns:
format(new Date(video?.createdAt), 'MMMM D, YYYY')
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.
I need to display the date on the format MM/dd/yyyy, hh:mm tt for the 'en' and 'es' locale. This approach works fine, but it displays the date as MM/dd/yy, showing only the last two digits for the year instead of the entrie year.
const en = new Intl.DateTimeFormat('en', { dateStyle: 'short', timeStyle: 'short', hour12: true }).format(new Date());
const es = new Intl.DateTimeFormat('es', { dateStyle: 'short', timeStyle: 'short', hour12: true }).format(new Date());
console.log('En', en, 'Es', es);
This approach
const en = (new Date()).toLocaleString('en');
const es = (new Date()).toLocaleString('es');
console.log('En', en, 'Es', es);
shows the full year, but it shows 24 hours format for the 'es' locale.
From here I have that when formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property. And this might be the case. How can I get this working?
I need to display the date on the format MM/dd/yyyy, hh:mm tt for the 'en' and 'es' locale.
Using a language code for say "es" then modifying the format is the antithesis of the purpose of the Intl object. It's supposed to format values based on the language tag provided and the results used unmodified.
Specific formats should be created manually or with a library (essentially the same thing). Spanish and English use the same characters for numbers, so the same timestamp can be presented for both languages if they don't have day or month names, e.g.
There are already a huge number of questions on how to format a javascript date. The following is an example using the Intl object:
// MM/dd/yyyy, hh:mm tt using Intl.DateTimeFormat
function formatDate(date) {
let p = new Intl.DateTimeFormat('en',{
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
hour12: true
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.month}/${p.day}/${p.year}, ${p.hour}:${p.minute} ${p.dayPeriod}`;
}
console.log(formatDate(new Date()));
Presenting dates in month/day/year order to Spanish readers is likely to greatly confuse them (and the vast majority of English speakers too). Pages are presented in a particular language, so all dates, numbers, etc. should follow the conventions of that language.
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));