leora
leora

Reputation: 196429

How do I format a date in JavaScript?

How do I format a Javascript Date object as a string? (Preferable format: 10-Aug-2010)

Upvotes: 3574

Views: 6898336

Answers (30)

Henadzi Rabkin
Henadzi Rabkin

Reputation: 7033

var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
console.log(formattedToday);

Upvotes: 12

KISHORE K J
KISHORE K J

Reputation: 615

Use "date-fns"

import { format } from "date-fns";

format(new Date(2024, 1, 24), "MM/dd/yyyy"); // '01/24/2024'
format(new Date(2024, 10, 6), 'MMM') //=> 'Nov'
format(new Date(2024, 10, 6), 'MMMM') //=> 'November'

Upvotes: 2

Sébastien
Sébastien

Reputation: 2083

Note (2022-10): toLocaleFormat has been deprecated for some time and was removed from Firefox as of version 58. See toLocaleFormat

I think you can just use the non-standard Date method toLocaleFormat(formatString)

formatString: A format string in the same format expected by the strftime() function in C.

    var today = new Date();
   today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
    

References:

Upvotes: 169

Kamran  Gasimov
Kamran Gasimov

Reputation: 1773

Example: "2023-04-25 00:01:23"

    var currentdate = new Date();
    var startedAt = currentdate.getFullYear() + "-" +
        (currentdate.getMonth() + 1).toString().padStart(2, '0') + "-" +
        currentdate.getDate().toString().padStart(2, '0') + " " +
        currentdate.getHours().toString().padStart(2, '0') + ":" +
        currentdate.getMinutes().toString().padStart(2, '0') + ":" +
        currentdate.getSeconds().toString().padStart(2, '0');
        
        console.log(startedAt)

Upvotes: 6

toddmo
toddmo

Reputation: 22396

TypeScript version

It can be easily enhanced to support any format string desired. When a generic solution like this is so easy to create, and date formatting comes up so often in applications, I wouldn't recommend hard-coding date format code all over your application. It's harder to read and hides your intentions. Format strings show your intentions clearly.

Prototype functions

interface Date {
    format(formatString: string): string;
}

Date.prototype.format = function (formatString: string): string {
  return Object.entries({
    YYYY: this.getFullYear(),
    YY: this.getFullYear().toString().substring(2),
    yyyy: this.getFullYear(),
    yy: this.getFullYear().toString().substring(2),
    MMMM: this.toLocaleString('default', { month: 'long' }),
    MMM: this.toLocaleString('default', { month: 'short' }),
    MM: (this.getMonth() + 1).toString().padStart(2, '0'),
    M: this.getMonth() + 1,
    DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
    DDD: this.toLocaleDateString('default', { weekday: 'short' }),
    DD: this.getDate().toString().padStart(2, '0'),
    D: this.getDate(),
    dddd: this.toLocaleDateString('default', { weekday: 'long' }),
    ddd: this.toLocaleDateString('default', { weekday: 'short' }),
    dd: this.getDate().toString().padStart(2, '0'),
    d: this.getDate(),
    HH: this.getHours().toString().padStart(2, '0'), // military
    H: this.getHours().toString(), // military
    hh: (this.getHours() % 12).toString().padStart(2, '0'),
    h: (this.getHours() % 12).toString(),
    mm: this.getMinutes().toString().padStart(2, '0'),
    m: this.getMinutes(),
    SS: this.getSeconds().toString().padStart(2, '0'),
    S: this.getSeconds(),
    ss: this.getSeconds().toString().padStart(2, '0'),
    s: this.getSeconds(),
    TTT: this.getMilliseconds().toString().padStart(3, '0'),
    ttt: this.getMilliseconds().toString().padStart(3, '0'),
    AMPM: this.getHours() < 13 ? 'AM' : 'PM',
    ampm: this.getHours() < 13 ? 'am' : 'pm',
  }).reduce((acc, entry) => {
    return acc.replace(entry[0], entry[1].toString())
  }, formatString)
}

Demo

function unitTest() {
    var d: Date = new Date()
    console.log(d.format('MM/dd/yyyy hh:mm:ss')) // 12/14/2022 03:38:31
    console.log(d.format('yyyy-MM-dd HH:mm:ss')) // 2022-12-14 15:38:31
}

unitTest()

JavaScript version

It's the same. Just remove the interface, and the type names after the colons and their associated colons.

Snippet

Date.prototype.format = function(formatString) {
  return Object.entries({
    YYYY: this.getFullYear(),
    YY: this.getFullYear().toString().substring(2),
    yyyy: this.getFullYear(),
    yy: this.getFullYear().toString().substring(2),
    MMMM: this.toLocaleString('default', { month: 'long'  }),
    MMM: this.toLocaleString('default',  { month: 'short' }),
    MM: (this.getMonth() + 1).toString().padStart(2, '0'),
    M: this.getMonth() + 1,
    DDDD: this.toLocaleDateString('default', { weekday: 'long'  }),
    DDD: this.toLocaleDateString('default',  { weekday: 'short' }),
    DD: this.getDate().toString().padStart(2, '0'),
    D: this.getDate(),
    dddd: this.toLocaleDateString('default', { weekday: 'long'  }),
    ddd: this.toLocaleDateString('default',  { weekday: 'short' }),
    dd: this.getDate().toString().padStart(2, '0'),
    d: this.getDate(),
    HH: this.getHours().toString().padStart(2, '0'), // military
    H: this.getHours().toString(), // military
    hh: (this.getHours() % 12).toString().padStart(2, '0'),
    h: (this.getHours() % 12).toString(),
    mm: this.getMinutes().toString().padStart(2, '0'),
    m: this.getMinutes(),
    SS: this.getSeconds().toString().padStart(2, '0'),
    S: this.getSeconds(),
    ss: this.getSeconds().toString().padStart(2, '0'),
    s: this.getSeconds(),
    TTT: this.getMilliseconds().toString().padStart(3, '0'),
    ttt: this.getMilliseconds().toString().padStart(3, '0'),
    AMPM: this.getHours() < 13 ? 'AM' : 'PM',
    ampm: this.getHours() < 13 ? 'am' : 'pm',
  }).reduce((acc, entry) => {
    return acc.replace(entry[0], entry[1].toString())
  }, formatString)
}



function unitTest() {
  var d = new Date()
  console.log(d.format('MM/dd/yyyy hh:mm:ss')) // 12/14/2022 03:38:31
  console.log(d.format('yyyy-MM-dd HH:mm:ss')) // 2022-12-14 15:38:31
}

unitTest()

Upvotes: 23

Samuel Reyes
Samuel Reyes

Reputation: 177

I have this code for adding days and format to a date.

 const FechaMaxima = new Date();
 FechaMaxima.setDate(FechaMaxima.getDate() + 6);
 FechaMaxima.toISOString().substring(0, 10);

Upvotes: 0

Mohsen Alyafei
Mohsen Alyafei

Reputation: 5537

The JavaScript Intl.DateTimeFormat method provides a convenient way to format dates.

Here is how the needed format can be constructed:

const date = new Date("2010-08-10");

let d=new Intl.DateTimeFormat('en-GB',{year:"numeric", month:"short",day:"2-digit"}).format(date).split(" ").join("-");

console.log(d);

Upvotes: 10

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20080

In my case, I have formatted the date from '01/07/2022' to '2022-07-01':

const formatDate = date => {
    const d = new Date(date)
    let month = (d.getMonth() + 1).toString()
    let day = d.getDate().toString()
    const year = d.getFullYear()
    if (month.length < 2) {
        month = '0' + month
    }
    if (day.length < 2) {
        day = '0' + day
    }
    return [ year, month, day ].join('-')
}

console.log(formatDate('01/07/2022'))

Upvotes: 2

saddam
saddam

Reputation: 196

Simply you can do this:

let date = new Date().toLocaleDateString('en-us', {day: 'numeric'})
let month = new Date().toLocaleDateString('en-us', {month: 'long'})
let year = new Date().toLocaleDateString('en-us', {year: 'numeric'})
const FormattedDate = `${date}-${month}-${year}`
console.log(FormattedDate) // 26-March-2022

Upvotes: 8

Weilory
Weilory

Reputation: 3101

String conversion


// date 
const dateConvert = {
  dasher: dt => {
    let m = (dt.getMonth() + 1) === 13 ? 1 : (dt.getMonth() + 1);
    m = m < 10 ? `0${m}` : m.toString();
    let d = dt.getDate();
    d = d < 10 ? `0${d}` : d.toString();
    return `${dt.getFullYear()}-${m}-${d}`;
  }, 
  slasher: dt => {
    return dateConvert.slash(dateConvert.dasher(dt));
  }, 
  dash: str => {
    // 03/11/2022 -> 2022-03-11
    let [d, m, y] = str.split('/');
    return `${y}-${m}-${d}`;
  }, 
  slash: str => {
    // 2022-03-11 -> 03/11/2022
    let [y, m, d] = str.split('-');
    return `${d}/${m}/${y}`
  }
}

// console.log(dateConvert.dasher(new Date('01/31/2001')));

Upvotes: 0

Yash Yadav
Yash Yadav

Reputation: 655

I just split it with 'T'

  date = "2023-11-15T00:00:00.000+00:00"
  myDate = date.split('T')[0]

Upvotes: -2

Marko
Marko

Reputation: 72222

For custom-delimited date formats, you have to pull out the date (or time) components from a DateTimeFormat object (which is part of the ECMAScript Internationalization API), and then manually create a string with the delimiters you want.

To do this, you can use DateTimeFormat#formatToParts. You could destructure the array, but that is not ideal, as the array output depends on the locale:

{ // example 1
   let formatter = new Intl.DateTimeFormat('en');
   let example = formatter.formatToParts();
   console.log(example);
}
{ // example 2
   let formatter = new Intl.DateTimeFormat('hi');
   let example = formatter.formatToParts();
   console.log(example);
}

Better would be to map a format array to resultant strings:

function join(date, options, separator) {
   function format(option) {
      let formatter = new Intl.DateTimeFormat('en', option);
      return formatter.format(date);
   }
   return options.map(format).join(separator);
}

let options = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let joined = join(new Date, options, '-');
console.log(joined);

You can also pull out the parts of a DateTimeFormat one-by-one using DateTimeFormat#format, but note that when using this method, as of March 2020, there is a bug in the ECMAScript implementation when it comes to leading zeros on minutes and seconds (this bug is circumvented by the approach above).

let date = new Date(2010, 7, 5);
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`${day}-${month}-${year}`);

When working with dates and times, it is usually worth using a library (eg. luxon, date-fns, moment.js is not recommended for new projects) because of the many hidden complexities of the field.

Note that the ECMAScript Internationalization API, used in the solutions above is not supported in IE10 (0.03% global browser market share in Feb 2020).

Upvotes: 1754

ajeet kanojia
ajeet kanojia

Reputation: 30613

If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.

Options key examples:

  1. day:
    The representation of the day.
    Possible values are "numeric", "2-digit".
  2. weekday:
    The representation of the weekday.
    Possible values are "narrow", "short", "long".
  3. year:
    The representation of the year.
    Possible values are "numeric", "2-digit".
  4. month:
    The representation of the month.
    Possible values are "numeric", "2-digit", "narrow", "short", "long".
  5. hour:
    The representation of the hour.
    Possible values are "numeric", "2-digit".
  6. minute: The representation of the minute.
    Possible values are "numeric", "2-digit".
  7. second:
    The representation of the second.
    Possible values are "numeric", 2-digit".
  8. hour12:
    The representation of time format.
    Accepts boolean true or false

All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.

Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.

For different languages:

  1. "en-US": For American English
  2. "en-GB": For British English
  3. "hi-IN": For Hindi
  4. "ja-JP": For Japanese

You can use more language options.

For example

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.

// Example
9/17/2016, 1:21:34 PM

References:

Upvotes: 3058

catwith
catwith

Reputation: 1265

Simple formatter:

function fmt(date, format = 'YYYY-MM-DDThh:mm:ss') {
  const pad2 = (n) => n.toString().padStart(2, '0');

  const map = {
    YYYY: date.getFullYear(),
    MM: pad2(date.getMonth() + 1),
    DD: pad2(date.getDate()),
    hh: pad2(date.getHours()),
    mm: pad2(date.getMinutes()),
    ss: pad2(date.getSeconds()),
  };

  return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}

// Usage
console.log(
  fmt(new Date(), 'YYYY-MM-DDThh:mm:ss') // '2023-03-04T10:30:24'
);
console.log(
  fmt(new Date(), 'MM/DD/YYYY, hh:mm:ss') // '03/04/2023, 10:30:24'
);

Upvotes: 11

Hitesh Chauhan
Hitesh Chauhan

Reputation: 1064

Formatting Date to different formats

let objectDate = new Date();



let day = objectDate.getDate();
console.log(day); // 12


let currentmo = objectDate.getMonth();
month = currentmo + 1;
console.log(month + 1); // 1


let year = objectDate.getFullYear();
console.log(year); // 2023



// Now you can set it accordingly


// dd/mm/yyyy
console.log(day + '/' + month + '/' + year);


// mm/dd/yyyy
console.log(month + '/' + day + '/' + year);

Try out this code - https://bbbootstrap.com/code/format-date-javascript-49065802

Upvotes: -3

ruffin
ruffin

Reputation: 17453

Though new Date().toISOString().slice(0, 10); is tres hipster and good for my normal use case, I didn't love any of the first few answers for a more customized string, and gave myself a few minutes to go as hipster golfy & one-linery as possible.

I didn't quite see the solution I came up with, so here it is...

((d,x)=>`${d.getFullYear()}-${x(d.getMonth()+1)}-${x(d.getDate())}`)
    (new Date(), (x)=>x.toString().padStart(2,"0"))

// today that produces
// '2022-09-28'
// the same as new Date().toISOString().slice(0, 10)
// but provides a good framework for other orders or values

Pseudo-IIFE for the win.

The problems solved here, of course, are...

  1. You may need to format days and months less than 10 with leading zeroes.
    • So pass in a function that casts to string & padStarts.
  2. You need to get the same date in there without going new Date() over and over.
    • Get "now" (new Date()) and pass in as a parameter to reuse.
  3. You gotta add 1 to getMonth.
    • Do that.

You could do similar tricks even if you needed to map to month abbreviations or something, not that it'd be very cute.

((d,x,y)=>`${x(d.getDate())} ${y(d.getMonth())} ${d.getFullYear()}`)
    (
     new Date(), 
     (x)=>x.toString().padStart(2,"0"), 
     (m)=>"jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec".split(',')[m]
    )

// As of this writing, that yields...
// '28 sep 2022'

(obviously remove whitespace from both for increased golfness; didn't want code blocks to scroll)

... though I'd have a hard time recommending that for anything but creating test values from the console for some strange reason. Really weird that there's no toString('yyyy-mm-dd'), and that's as close as I could get in a line.

Upvotes: 0

Lewis Nakao
Lewis Nakao

Reputation: 7362

Packaged Solution: Luxon or date-fns

If you want to use a one solution to fit all, I recommend using date-fns or Luxon.

Luxon is hosted on the Moment.js website and developed by a Moment.js developer because Moment.js has limitations that the developer wanted to address but couldn't.

To install:

npm install luxon or yarn add luxon (visit link for other installation methods)

Example:

luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LLL-dd');

Yields:

10-Aug-2010

Manual Solution

Using similar formatting as Moment.js, Class DateTimeFormatter (Java), and Class SimpleDateFormat (Java), I implemented a comprehensive solution formatDate(date, patternStr) where the code is easy to read and modify. You can display date, time, AM/PM, etc. See code for more examples.

Example:

formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss:S')

(formatDate is implemented in the code snippet below)

Yields:

Friday, October 12, 2018 18:11:23:445

Try the code out by clicking "Run code snippet."

Date and Time Patterns

yy = 2-digit year; yyyy = full year

M = digit month; MM = 2-digit month; MMM = short month name; MMMM = full month name

EEEE = full weekday name; EEE = short weekday name

d = digit day; dd = 2-digit day

h = hours am/pm; hh = 2-digit hours am/pm; H = hours; HH = 2-digit hours

m = minutes; mm = 2-digit minutes; aaa = AM/PM

s = seconds; ss = 2-digit seconds

S = miliseconds

var monthNames = [
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, patternStr){
    if (!patternStr) {
        patternStr = 'M/d/yyyy';
    }
    var day = date.getDate(),
        month = date.getMonth(),
        year = date.getFullYear(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        miliseconds = date.getMilliseconds(),
        h = hour % 12,
        hh = twoDigitPad(h),
        HH = twoDigitPad(hour),
        mm = twoDigitPad(minute),
        ss = twoDigitPad(second),
        aaa = hour < 12 ? 'AM' : 'PM',
        EEEE = dayOfWeekNames[date.getDay()],
        EEE = EEEE.substr(0, 3),
        dd = twoDigitPad(day),
        M = month + 1,
        MM = twoDigitPad(M),
        MMMM = monthNames[month],
        MMM = MMMM.substr(0, 3),
        yyyy = year + "",
        yy = yyyy.substr(2, 2)
    ;
    // checks to see if month name will be used
    patternStr = patternStr
      .replace('hh', hh).replace('h', h)
      .replace('HH', HH).replace('H', hour)
      .replace('mm', mm).replace('m', minute)
      .replace('ss', ss).replace('s', second)
      .replace('S', miliseconds)
      .replace('dd', dd).replace('d', day)
      
      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
      .replace('aaa', aaa);
    if (patternStr.indexOf('MMM') > -1) {
        patternStr = patternStr
          .replace('MMMM', MMMM)
          .replace('MMM', MMM);
    }
    else {
        patternStr = patternStr
          .replace('MM', MM)
          .replace('M', M);
    }
    return patternStr;
}
function twoDigitPad(num) {
    return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP's request
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S'));
console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa'));

Thank you @Gerry for bringing up Luxon.

Upvotes: 58

Mr Nsubuga
Mr Nsubuga

Reputation: 292

This may help with the problem:

var d = new Date();

var options = {   
    day: 'numeric',
    month: 'long', 
    year: 'numeric'
};

console.log(d.toLocaleDateString('en-ZA', options));

Upvotes: 23

Agi Hammerthief
Agi Hammerthief

Reputation: 2134

The following code will allow you to format the date to either DD-MM-YYYY (27-12-2017) or DD MMM YYYY (27 Dec 2017) :

/** Pad number to fit into nearest power of 10 */
function padNumber(number, prependChar, count) {
  var out = '' + number; var i;
  if (number < Math.pow(10, count))
    while (out.length < ('' + Math.pow(10, count)).length) out = prependChar + out;
  
  return out;
}

/* Format the date to 'DD-MM-YYYY' or 'DD MMM YYYY' */
function dateToDMY(date, useNumbersOnly) {
  var months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
    'Nov', 'Dec'
  ];

  return '' + padNumber(date.getDate(), '0', 1) + 
   (useNumbersOnly? '-' + padNumber(date.getMonth() + 1, '0', 1) + '-' : ' ' + months[date.getMonth()] + ' ')
    + date.getFullYear();
}

Change the order of date.getFullYear() and padNumber(date.getDate(), '0', 1) to make a dateToYMD() function.

See repl.it example for details.

Upvotes: 1

perepm
perepm

Reputation: 980

The Date constructor (and Date.parse()) only accepts one format as a parameter when constructing a date and that is ISO 8601:

// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')

But parsing a from a string is strongly discouraged (MDN recommends against creating date with date strings) due to browser differences and inconsistencies.

The recommended alternative would be building your Date instance directly from the numeric data like this:

new Date(2017, 7, 15) // Month is zero-indexed

That is parsing. Now, to format your date to the string you desire you have several options that are native of the Date object (although I believe none is compliant to the format you require):

date.toString()       // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString()   // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString()    // '2019-01-23T09:23:42.079Z'

For other formatting options I'm afraid you'll have to turn to libraries such as Moment.js, day.js and the like.

Credit to Zell Liew from this article for the date formatting tips.

Upvotes: 37

simo
simo

Reputation: 15478

Well, what I wanted was to convert today's date to a MySQL friendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:

var today = new Date().toISOString().slice(0, 10);

Keep in mind that the above solution does not take into account your timezone offset.

You might consider using this function instead:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

This will give you the correct date in case you are executing this code around the start/end of the day.

var date = new Date();

function toLocal(date) {
  var local = new Date(date);
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  return local.toJSON();
}

function toJSONLocal(date) {
  var local = new Date(date);
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  return local.toJSON().slice(0, 10);
}

// check out your devtools console
console.log(date.toJSON());
console.log(date.toISOString());
console.log(toLocal(date));

console.log(toJSONLocal(date));

Upvotes: 593

Louis Semprini
Louis Semprini

Reputation: 3813

Here is some ready-to-paste time/date formatting code that does not rely on any external modules/libraries or use jQuery or ES7 or anything. Unlike the code in some other answers, this code offers this combination of features:

  • it takes a JavaScript Date object as input
  • it can display date as local time zone or UTC
  • it uses a simple formatting system "{year4} {month02} {second}" that is easy to read and understand even after you write the code, unlike the typical "%D %m %-" which always forces you back to the documentation
  • the formatting system does not have any weird self-collisions like some ad-hoc "DD MM YYYY" systems
  • you can run the test right here and try it

// format_date(date, pattern, utc)
// - date
//   - a JavaScript Date object
//   - use "new Date()" for current time
// - pattern
//   - a string with embedded {codes} like
//     "{year4}-{month02}-{day02}: {dayname3}"
//     see format_date_funcs below for complete list
//   - any other letters go through unchanged
// - utc
//   - if true, shows date in UTC time "zone"
//   - if false/omitted, shows date in local time zone
//
var month_names =
[
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var day_of_week_names =
[
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];

function space_pad2(num)
{
    return num < 10 ? " " + num : num;
}

function zero_pad2(num)
{
    return num < 10 ? "0" + num : num;
}

function space_pad3(num)
{
    if (num < 10)
        return "  " + num;
    else if (num < 100)
        return " " + num;
    else
        return num;
}

function zero_pad3(num)
{
    if (num < 10)
        return "00" + num;
    else if (num < 100)
        return "0" + num;
    else
        return num;
}

var format_date_funcs =
{
    // {year4}  = '1902'
    // {year02} =   '02'
    //
    'year4': function(date, utc)
    {
        var year = utc ? date.getUTCFullYear() : date.getFullYear();
        return year;
    },
    'year02': function(date, utc)
    {
        var year = utc ? date.getUTCFullYear() : date.getFullYear();
        return year.toString().substr(2,2);
    },
    // {month}   =  '1' - '12'
    // {month2}  = ' 1' - '12' (space padded)
    // {month02} = '01' - '12'
    //
    'month': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return            month + 1;
    },
    'month2': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return space_pad2(month + 1);
    },
    'month02': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return zero_pad2(month + 1);
    },
    // {monthname}  = 'January'
    // {monthname3} = 'Jan'
    //
    'monthname': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return month_names[month];
    },
    'monthname3': function(date, utc)
    {
        var month = utc ? date.getUTCMonth() : date.getMonth(); // [0,11]
        return month_names[month].substr(0, 3);
    },
    // {day}   =  '1' - '31'
    // {day2}  = ' 1' - '31' (space padded)
    // {day02} = '01' - '31'
    //
    'day': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return date;
    },
    'day2': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return space_pad2(date);
    },
    'day02': function(date, utc)
    {
        var date = utc ? date.getUTCDate() : date.getDate(); // [1,31]
        return zero_pad2(date);
    },
    // {dayname}  = 'Tuesday'
    // {dayname3} = 'Tue'
    //
    'dayname': function(date, utc)
    {
        var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
        return day_of_week_names[day];
    },
    'dayname3': function(date, utc)
    {
        var day = utc ? date.getUTCDay() : date.getDay(); // [0,6]
        return day_of_week_names[day].substr(0,3);
    },
    // {24hour}   =  '0' - '23'
    // {24hour2}  = ' 0' - '23' (space padded)
    // {24hour02} = '00' - '23'
    //
    '24hour': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return hour;
    },
    '24hour2': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return space_pad2(hour);
    },
    '24hour02': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return zero_pad2(hour);
    },
    // {12hour}   =  '1' - '12'
    // {12hour2}  = ' 1' - '12' (space padded)
    // {12hour02} = '01' - '12'
    // {ampm}     = 'am' or 'pm'
    // {AMPM}     = 'AM' or 'PM'
    //
    '12hour': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return hour;
    },
    '12hour2': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return space_pad2(hour);
    },
    '12hour02': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        hour = hour % 12; // [0,11]
        if (0 === hour) hour = 12;
        return zero_pad2(hour);
    },
    'ampm': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return (hour < 12 ? 'am' : 'pm');
    },
    'AMPM': function(date, utc)
    {
        var hour = utc ? date.getUTCHours() : date.getHours(); // [0,23]
        return (hour < 12 ? 'AM' : 'PM');
    },
    // {minute}   =  '0' - '59'
    // {minute2}  = ' 0' - '59' (space padded)
    // {minute02} = '00' - '59'
    //
    'minute': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return minute;
    },
    'minute2': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return space_pad2(minute);
    },
    'minute02': function(date, utc)
    {
        var minute = utc ? date.getUTCMinutes() : date.getMinutes(); // [0,59]
        return zero_pad2(minute);
    },
    // {second}   =  '0' - '59'
    // {second2}  = ' 0' - '59' (space padded)
    // {second02} = '00' - '59'
    //
    'second': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return second;
    },
    'second2': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return space_pad2(second);
    },
    'second02': function(date, utc)
    {
        var second = utc ? date.getUTCSeconds() : date.getSeconds(); // [0,59]
        return zero_pad2(second);
    },
    // {msec}   =   '0' - '999'
    // {msec3}  = '  0' - '999' (space padded)
    // {msec03} = '000' - '999'
    //
    'msec': function(date, utc)
    {
        var msec =
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return msec;
    },
    'msec3': function(date, utc)
    {
        var msec =
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return space_pad3(msec);
    },
    'msec03': function(date, utc)
    {
        var msec =
            utc ? date.getUTCMilliseconds() : date.getMilliseconds(); // [0,999]
        return zero_pad3(msec);
    },
    // {open} = '{' (in case you actually want '{' in the output)
    //
    'open': function(date, utc)
    {
        return '{';
    },
    // {close} = '}' (in case you actually want '}' in the output)
    //
    'close': function(date, utc)
    {
        return '}';
    },
};

function format_date(date, pattern, utc)
{
    if (!pattern)
    {
        pattern = '{month}/{day}/{year4}';
    }

    var ret = '';

    while (pattern.length > 0)
    {
        var s = pattern.indexOf('{');
        var e = pattern.indexOf('}');
        //console.log('s ' + s + ' e ' + e);
        if (-1 !== s && -1 !== e && s < e)
        {
            // - there is a well-formed {foo} in range [s,e]
            // - first we emit range [0,s) as literal
        }
        else
        {
            // - rest of string has no {} or has malformed }{ or { or }
            // - just emit the rest of the string as literal and be done
            s = pattern.length;
        }
        // emit range [0,s) as literal
        if (s > 0)
        {
            ret += pattern.substr(0, s);
            pattern = pattern.substr(s);
            e -= s;
            s = 0;
        }

        if (0 === pattern.length) break;

        // emit range [s=0,e] by evaluating code
        console.assert(0 === s); // position of {
        console.assert(e > 0);  // position of }
        console.assert('{' === pattern.substr(s, 1));
        console.assert('}' === pattern.substr(e, 1));
        var code = pattern.substr(1,e-1);
        var func = format_date_funcs[code];
        console.assert(func);
        ret += func(date, utc);

        pattern = pattern.substr(e+1);
    }

    return ret;
}

if (1) // test format_date
{
    var fmt = '[';
    for (var func in format_date_funcs)
    {
        if (!format_date_funcs.hasOwnProperty(func)) continue;
        fmt += '{' + func + '}/';
    }
    fmt += ']';
    var now = new Date();
    console.log(fmt);
    console.log(format_date(now, fmt, false /* utc */));
    console.log(format_date(now, fmt, true /* utc */));
}

Upvotes: 0

Guilherme Oliveira
Guilherme Oliveira

Reputation: 2369

This module can easily handle mostly every case there is. It is part of a bigger npm package, by Locutus, which includes a variety of functions, but it can be used totally independent of the package itself, just copy paste/ adapt a little if not working with npm (change from a module to just a function).

As a second parameter it accepts a timestamp, which can come from anywhere, such as Date.getTime().

Also, Locutus maintains a bigger datetime module, also inside the locutus package which will give a more object-oriented way to use it.

Here you can see other datetime functions, as modules, that proved to be very useful too.

You can find documentation on parameters and format strings here (note that the documentation site is a PHP site, but the locutus implementation follows exactly the same specifications).

Examples of the date Module

date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'

date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'

date('Y W o', 1062462400)//'2003 36 2003'

var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09    10

date('W', 1104534000)    //'52'

date('B t', 1104534000)    //'999 31'

date('W U', 1293750000.82); // 2010-12-31    '52 1293750000'

date('W', 1293836400); // 2011-01-01    '52'

date('W Y-m-d', 1293974054); // 2011-01-02    '52 2011-01-02'

Upvotes: 1

riversun
riversun

Reputation: 838

This function was inspired by Java's SimpleDateFormat provides various formats such as:

dd-MMM-yyyy → 17-Jul-2018
yyyyMMdd'T'HHmmssXX → 20180717T120856+0900
yyyy-MM-dd'T'HH:mm:ssXXX → 2018-07-17T12:08:56+09:00
E, dd MMM yyyy HH:mm:ss Z → Tue, 17 Jul 2018 12:08:56 +0900
yyyy.MM.dd 'at' hh:mm:ss Z → 2018.07.17 at 12:08:56 +0900
EEE, MMM d, ''yy → Tue, Jul 17, '18
h:mm a → 12:08 PM
hh 'o''''clock' a, X → 12 o'clock PM, +09

Code example:

function formatWith(formatStr, date, opts) {

    if (!date) {
        date = new Date();
    }

    opts = opts || {};

    let _days = opts.days;

    if (!_days) {
        _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    }

    let _months = opts.months;

    if (!_months) {
        _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    }

    const pad = (number, strDigits, isUnpad) => {
        const strNum = number.toString();
        if (!isUnpad && strNum.length > strDigits.length) {
            return strNum;
        } else {
            return ('0000' + strNum).slice(-strDigits.length);
        }
    };

    const timezone = (date, letter) => {
        const chunk = [];
        const offset = -date.getTimezoneOffset();
        chunk.push(offset === 0 ? 'Z' : offset > 0 ? '+' : '-');//add Z or +,-
        if (offset === 0) return chunk;
        chunk.push(pad(Math.floor(offset / 60), '00'));//hour
        if (letter === 'X') return chunk.join('');
        if (letter === 'XXX') chunk.push(':');
        chunk.push(pad((offset % 60), '00'));//min
        return chunk.join('');
    };

    const ESCAPE_DELIM = '\0';
    const escapeStack = [];

    const escapedFmtStr = formatStr.replace(/'.*?'/g, m => {
        escapeStack.push(m.replace(/'/g, ''));
        return ESCAPE_DELIM + (escapeStack.length - 1) + ESCAPE_DELIM;
    });

    const formattedStr = escapedFmtStr
        .replace(/y{4}|y{2}/g, m => pad(date.getFullYear(), m, true))
        .replace(/M{3}/g, m => _months[date.getMonth()])
        .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
        .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
        .replace(/d{1,2}/g, m => pad(date.getDate(), m))
        .replace(/H{1,2}/g, m => pad(date.getHours(), m))
        .replace(/h{1,2}/g, m => {
            const hours = date.getHours();
            return pad(hours === 0 ? 12 : hours > 12 ? hours - 12 : hours, m);
        })
        .replace(/a{1,2}/g, m => date.getHours() >= 12 ? 'PM' : 'AM')
        .replace(/m{1,2}/g, m => pad(date.getMinutes(), m))
        .replace(/s{1,2}/g, m => pad(date.getSeconds(), m))
        .replace(/S{3}/g, m => pad(date.getMilliseconds(), m))
        .replace(/[E]+/g, m => _days[date.getDay()])
        .replace(/[Z]+/g, m => timezone(date, m))
        .replace(/X{1,3}/g, m => timezone(date, m))
    ;

    const unescapedStr = formattedStr.replace(/\0\d+\0/g, m => {
        const unescaped = escapeStack.shift();
        return unescaped.length > 0 ? unescaped : '\'';
    });

    return unescapedStr;
}

// Let's format with above function
const dateStr = '2018/07/17 12:08:56';
const date = new Date(dateStr);
const patterns = [
    "dd-MMM-yyyy",
    "yyyyMMdd'T'HHmmssXX",//ISO8601
    "yyyy-MM-dd'T'HH:mm:ssXXX",//ISO8601EX
    "E, dd MMM yyyy HH:mm:ss Z",//RFC1123(RFC822) like email
    "yyyy.MM.dd 'at' hh:mm:ss Z",//hh shows 1-12
    "EEE, MMM d, ''yy",
    "h:mm a",
    "hh 'o''''clock' a, X",
];

for (let pattern of patterns) {
    console.log(`${pattern} → ${formatWith(pattern, date)}`);
}

And you can use this as a library

It is also released as an NPM module. You can use this on Node.js or use this from a CDN for a browser.

Node.js

const {SimpleDateFormat} = require('@riversun/simple-date-format');

In the browser

<script src="https://cdn.jsdelivr.net/npm/@riversun/[email protected]/dist/simple-date-format.js"></script>

Write the code as follows.

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

Source code here on GitHub:

https://github.com/riversun/simple-date-format

Upvotes: 2

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

Two pure JavaScript one-liners

In this answer I develop JD Smith's idea. I was able to shorten the JD Smith regexp.

let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');

console.log( format(Date()) );

Dave's is also based on JD Smith's idea, but he avoids regexps and give a very nice solution - I short his solution a little (by changing the split parameter) and opaque it in a wrapper.

let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];

console.log( format(Date()) );

Upvotes: 7

Prabha
Prabha

Reputation: 273

Maybe this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using the Moment.js format function on a current date as (today is 29-06-2020): var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

It retains only the year part: 20 as "06/28/20", after if I run the statement new Date(startDate), the result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)".

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in Google Chrome and Firefox browsers, it gives the correct date on the second attempt as: 06-28-2020.

But in Internet Explorer it is having issues. From this I understood we can apply one dateformat on the given date. If we want a second date format, it should be apply on the fresh date, not on the first date format result. And also observe that for the first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in Internet Explorer. For a clear understanding, please find my question in the link: Date went wrong when using Moment.js date format in Internet Explorer 11.

Upvotes: 0

Jan
Jan

Reputation: 2249

It works same in Internet Explorer 11, Firefox, and Chrome (Chrome 80.x shows 12 hours format when en-UK selected).

const d = new Date('2010/08/05 23:45') // 26.3.2020
const dtfUK = new Intl.DateTimeFormat('UK', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
console.log(dtfUS.format(d)); // 08/05/2010 11:45:00 PM
console.log(dtfUK.format(d)); // 05.08.2010 23:45:00
/* node.js:
08/05/2010, 11:45:00 PM
2010-08-05 23:45:00
*/

What about something more general?

var d = new Date('2010-08-10T10:34:56.789Z');
var str = d.toDateString() + // Tue Aug 10 2010
    ' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00)
    ' ' + (d.getMonth() + 101) + // 108
    ' ' + d.getMilliseconds(); // 789
console.log(str); // Tue Aug 10 2010 12:34:56 108 789
console.log(//   $1 Tue  $2 Aug  $3 11     $4 2020 $5 12   $6 34   $7 56    $8 108  $9 789
    str.replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, '$3-$2-$4 $5:$6.$9 ($1)')
); // 10-Aug-2010 12:34.789 (Tue)
/*
$1: Tue  Week Day string
$2: Aug  Month short text
$3: 11   Day
$4: 2010 Year
$5: 12   Hour
$6: 34   Minute
$7: 56   Seconds
$8: 08   Month
$9: 789  Milliseconds
*/

Or for example 1-line IIFE "library" ;-)

console.log(
    (function (frm, d) { return [d.toDateString(), d.toTimeString().split(' ')[0], (d.getMonth() + 101), d.getMilliseconds()].join(' ').replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, frm); })
    ('$4/$8/$3 $5:$6 ($1)', new Date())
);

You can remove useless parts and / or change indexes if you do not need them.

Upvotes: 10

moshfiqrony
moshfiqrony

Reputation: 4723

Use this procedure

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']

const date = new Date()

const dateString = `${date.getDate()}-${MONTHS[date.getMonth()]}-${date.getFullYear()}`

console.log(dateString)

Upvotes: 2

Adrian Maire
Adrian Maire

Reputation: 14815

Custom formatting function:

For fixed formats, a simple function make the job. The following example generates the international format YYYY-MM-DD:

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1; //Month from 0 to 11
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

The OP format may be generated like:

function dateToYMD(date) {
    var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var d = date.getDate();
    var m = strArray[date.getMonth()];
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5

Note: It is, however, usually not a good idea to extend the JavaScript standard libraries (e.g. by adding this function to the prototype of Date).

A more advanced function could generate configurable output based on a format parameter.

If to write a formatting function is too long, there are plenty of libraries around which does it. Some other answers already enumerate them. But increasing dependencies also has it counter-part.

Standard ECMAScript formatting functions:

Since more recent versions of ECMAScript, the Date class has some specific formatting functions:

toDateString: Implementation dependent, show only the date.

https://262.ecma-international.org/#sec-date.prototype.todatestring

new Date().toDateString(); // e.g. "Fri Nov 11 2016"

toISOString: Show ISO 8601 date and time.

https://262.ecma-international.org/#sec-date.prototype.toisostring

new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"

toJSON: Stringifier for JSON.

https://262.ecma-international.org/#sec-date.prototype.tojson

new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"

toLocaleDateString: Implementation dependent, a date in locale format.

https://262.ecma-international.org/#sec-date.prototype.tolocaledatestring

new Date().toLocaleDateString(); // e.g. "21/11/2016"

toLocaleString: Implementation dependent, a date&time in locale format.

https://262.ecma-international.org/#sec-date.prototype.tolocalestring

new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"

toLocaleTimeString: Implementation dependent, a time in locale format.

https://262.ecma-international.org/#sec-date.prototype.tolocaletimestring

new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"

toString: Generic toString for Date.

https://262.ecma-international.org/#sec-date.prototype.tostring

new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"

Note: it is possible to generate custom output out of those formatting >

new Date().toISOString().slice(0,10); //return YYYY-MM-DD

Examples snippets:

console.log("1) "+  new Date().toDateString());
console.log("2) "+  new Date().toISOString());
console.log("3) "+  new Date().toJSON());
console.log("4) "+  new Date().toLocaleDateString());
console.log("5) "+  new Date().toLocaleString());
console.log("6) "+  new Date().toLocaleTimeString());
console.log("7) "+  new Date().toString());
console.log("8) "+  new Date().toISOString().slice(0,10));

Specifying the locale for standard functions:

Some of the standard functions listed above are dependent on the locale:

  • toLocaleDateString()
  • toLocaleTimeString()
  • toLocalString()

This is because different cultures make uses of different formats, and express their date or time in different ways. The function by default will return the format configured on the device it runs, but this can be specified by setting the arguments (ECMA-402).

toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');

The option second parameter, allow for configuring more specific format inside the selected locale. For instance, the month can be show as full-text or abreviation.

toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })

Examples snippets:

console.log("1) "+  new Date().toLocaleString('en-US'));
console.log("2) "+  new Date().toLocaleString('ko-KR'));
console.log("3) "+  new Date().toLocaleString('de-CH'));

console.log("4) "+  new Date().toLocaleString('en-GB', { hour12: false }));
console.log("5) "+  new Date().toLocaleString('en-GB', { hour12: true }));

Some good practices regarding locales:

  • Most people don't like their dates to appear in a foreigner format, consequently, keep the default locale whenever possible (over setting 'en-US' everywhere).
  • Implementing conversion from/to UTC can be challenging (considering DST, time-zone not multiple of 1 hour, etc.). Use a well-tested library when possible.
  • Don't assume the locale correlate to a country: several countries have many of them (Canada, India, etc.)
  • Avoid detecting the locale through non-standard ways. Here you can read about the multiple pitfalls: detecting the keyboard layout, detecting the locale by the geographic location, etc..

Upvotes: 431

user956584
user956584

Reputation: 5559

@Sébastien -- alternative all browser support

new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString


High-order tagged template literal example based on Date.toLocaleDateString:

const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
    str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')

console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"

Upvotes: 51

Related Questions