Skip to content Skip to sidebar Skip to footer

How Do I Format A Date Object With Users Preference Instead Of Locale?

EDIT: I think it's crazy that JavaScript can talk to USB devices but can't simply pull the OS' preferred date format. Doing more research, this question is a duplicate of Javascrip

Solution 1:

The correct answer (at least today) seems to be that this is not possible. I have found this duplicate question that has no answers on it: Javascript - Retrieve OS Date formatting.

If anybody knows the actual answer to this question, answer this other question instead.

Solution 2:

You can add parameters to the .toLocalString() method.

en-us format: MM/dd/yy h:mm a
newDate().toLocaleString('en-us', { timeZone: 'UTC' })
returns "3/11/2020, 3:02:21 PM"
en-gb format: DD/MM/YYYHH:MMnewDate().toLocaleString('en-gb', { timeZone: 'UTC' })
returns "11/03/2020, 15:02:26"

BTW: .toLocalString() looks at the browsers settings, not the OS's.

Solution 3:

If you prefer not using momentjs and do it yourself,You can extract individual values like this and format into any format you want

const dateValue = newDate(dateString);
const dd = dateValue.getDate();
constMM = dateValue.getMonth() + 1;
const yyyy = dateValue.getFullYear();

For example to convert today's date to mm/dd/yyyy format

const date=newDate();
console.log(date);

constformatDate=(dateString,requiredFormat)=>{
const dd=dateString.getDate();
const mm=dateString.getMonth()+1;
const yyyy=dateString.getFullYear();
 if(requiredFormat.toLowerCase()==='mm/dd/yyyy')
   return`${mm}/${dd}/${yyyy}`
}

console.log(formatDate(date,'mm/dd/yyyy'));

Post a Comment for "How Do I Format A Date Object With Users Preference Instead Of Locale?"