Skip to content

Instantly share code, notes, and snippets.

@massahud
Created December 14, 2016 11:53
Show Gist options
  • Save massahud/5529c09fec28af58810fddc671639e42 to your computer and use it in GitHub Desktop.
Save massahud/5529c09fec28af58810fddc671639e42 to your computer and use it in GitHub Desktop.
Date to locale string in javascript
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
let year = 'numeric';
let month = '2-digit';
let day = '2-digit';
let hour = '2-digit';
let minute = '2-digit';
let second = '2-digit';
let hour12 = false;
let weekday = 'short';
let era = 'narrow';
let timeZoneName='long';
let timeZone = 'America/Sao_Paulo';
let now = new Date();
console.log(now.toLocaleString('pt-br',{year, month, day, hour, minute, second, hour12, weekday, era, timeZoneName, timeZone}));
console.log(now.toLocaleString('pt-pt',{year, month, day, hour, minute, second, hour12, weekday, era, timeZoneName, timeZone}));
console.log(now.toLocaleString('en-us',{year, month, day, hour, minute, second, hour12, weekday, era, timeZoneName, timeZone}));
console.log(now.toLocaleString(undefined,{year, month, day, hour, minute, second, hour12, weekday, era, timeZoneName, timeZone}));
console.log(now.toLocaleString(undefined,{year, month, day}));
console.log(now.toLocaleString(undefined,{year, month, day, hour, minute, second}));
console.log(now.toLocaleString(undefined,{year, month, day, hour, minute, second, hour12}));
month='long';
day='numeric';
console.log(now.toLocaleString(undefined,{year, month, day, hour, minute, second, hour12}));
timeZoneName='short';
console.log(now.toLocaleString(undefined,{hour, minute, second, timeZoneName}));
weekday = 'long';
console.log(now.toLocaleString(undefined,{weekday}));
weekday = 'narrow';
console.log(now.toLocaleString(undefined,{weekday}));
month = 'narrow';
console.log(now.toLocaleString(undefined,{month}));
month = 'short';
year='2-digit';
console.log(now.toLocaleString(undefined,{day, month, year}));
timeZone='GMT';
let with1digits = new Date('2009-02-03T01:02:03Z')
day = month = year= hour = minute = second = '2-digit';
hour12 = true;
console.log(with1digits.toLocaleString(undefined,{hour,minute,second,day,month,year,timeZone,hour12}));
day = month = hour = minute = second = 'numeric';
console.log(with1digits.toLocaleString(undefined,{hour,minute,second,day,month,year,timeZone,hour12}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment