suppose if we have a date 2 dec 2016
and
browser locale is en-UK
i need to display like 12/02
if browser locale is en-US
i need to display like 02/12
i dont want to display year
suppose if we have a date 2 dec 2016
and
browser locale is en-UK
i need to display like 12/02
if browser locale is en-US
i need to display like 02/12
i dont want to display year
We can use the toLocaleDateString to get a local-based date string.
If no date is supplied, we can use today’s date.
If no locale is supplied, we can leave it undefined to use the users locale.
function getLocaleDate(date, locale) {
return new Date(date).toLocaleDateString(locale);
}
var date = new Date(), // today's date
localeDate = getLocaleDate(date);
console.log(localeDate);
// → 4/9/2016
Options can be added to specify the format. Details on the options are found at the toLocaleDateString page.
As you want the day and month to be two-digit, you can add those options:
function getLocaleDate(date, locale, options) {
return new Date(date).toLocaleDateString(locale, options);
}
var date = new Date(), // today's date
locale, // leave undefined for users locale
options = {day: "2-digit", month: "2-digit"},
localeDate = getLocaleDate(date, locale, options);
console.log(localeDate);
// → 04/09
And by using those options, it also helps to remove the unwanted year too.
Haha, I thought of toLocaleString
, but not of simply slicing the first 5 characters. :-D
You should check if it’s either GB or US then though, other countries may have yet a different notation where this approach doesn’t work.
I was in the process of testing it then. The slicing is now no longer needed (and the code updated), and even simpler when you specify the date options.
This means that checking the country type is no longer an issue too
Here are some good details on toLocaleDateString
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.