Reputation: 1541
Hi I have used toLocaleDateString()
to display a date from a rss feed,t its not showing dd/mm/yyyy
format in all browser, safari and mozila its showing differently but chrome it is showing correctly.
Upvotes: 21
Views: 71995
Reputation: 1903
I was looking for an answer to this question, but above answers doesn't give a crip answer for converting date to dd/mm/yyyy
using toLocaleDateString()
.
As per docs toLocaleDateString()
converts a date to a string with a language sensitive representation of the date portion. This method accepts two parameters dateObj.toLocaleDateString( [locales][, options])
described below :
locales: This parameter is an array of locale strings that contain one or more language or locale tags.Note that it is an optional parameter.If you want to use specific format of the language in your application then specify that language in the locales argument.Some parameters are:
options: It is also an optional parameter and contains properties that specify comparison options.Some properties are localeMatcher, timeZone, weekday, year, month, day, hour, minute, second etc.
So using this here is how you can convert date to dd/mm/yyyy
format:
let dateFormat=new Date().toLocaleDateString('en-GB', {
month: '2-digit',day: '2-digit',year: 'numeric'})
console.log(dateFormat)
for persian date (current date)
const p2e = s => s.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d))
const dateFormat = p2e(new Date().toLocaleDateString('fa-IR', { month: '2-digit', day: '2-digit', year: 'numeric' }))
console.log(dateFormat)
Upvotes: 18
Reputation: 89
In Chrome you need to go to the Advanced>Language settings. Then drop down the top "Language" section and you will probably see a few variations of English.
Ensure that you select "Display Google Chrome in this language" for the version of English you want - it doesn't matter whether it is at the top of the list.
Upvotes: 0
Reputation: 1419
This has already been answered before:
According to the Mozilla documentation, the format can vary wildly depending on the user's location and computer settings.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
The exact format depends on the platform, locale and user's settings.
.toLocaleDateString() Not Working in Firefox
Upvotes: 5
Reputation: 324620
toLocaleDateString
is intended to provide a human-readable format, according to the rules of the user's own computer. For instance, if my computer is set to French, it might include the day name in French.
toLocaleDateString
is NOT a reliable way of getting the format you want. Instead, do this:
var dateobj = new Date();
function pad(n) {return n < 10 ? "0"+n : n;}
var result = pad(dateobj.getDate())+"/"+pad(dateobj.getMonth()+1)+"/"+dateobj.getFullYear();
Upvotes: 31