DEV Community

Cover image for Format Date and Time with Vanilla JavaScript
bob.ts
bob.ts

Posted on

Format Date and Time with Vanilla JavaScript

I've used a variety of tools over the years to manage date and time functionality in JavaScript. Here I am documenting the Vanilla JavaScript patterns for my own use.

See Intl.DateTimeFormat() constructor for reference information beyond what is in this article.

Date.prototype.toLocaleString

There is also a generic method called toLocaleString and it can take all of the options from the toLocaleDateString and toLocaleTimeString methods.

Support

CanIUse Support

const date = new Date();

const options1 = {
  month: 'short'
};

console.log(date.toLocaleString('en-US', options1));
// Aug

const options2 = {
  hour: '2-digit'
};

console.log(date.toLocaleString('en-US', options2));
// 1 PM

const dateOptions = {
  weekday: 'long',
  day: 'numeric',
  month: 'long',
  year: 'numeric'
};
const timeOptions = {
  hour12: true,
  hour: 'numeric',
  minute: '2-digit',
  second: '2-digit',
};

const options3 = {
  ...timeOptions, ... dateOptions
};

console.log(date.toLocaleString('en-US', options3));
// Monday, Aug 10, 2020, 1:44:27 PM
Enter fullscreen mode Exit fullscreen mode

Date.prototype.toLocaleDateString

The method accepts a locale and an optional options parameter where you can pass one or more flags to control the output behavior.

Support

CanIUse Support

const date = new Date();

console.log(date.toLocaleDateString('en-US'));
// 8/10/2020

const dateOptions1 = {
  weekday: 'long',
  day: 'numeric',
  month: 'long',
  year: 'numeric'
};

console.log(date.toLocaleDateString('en-US, dateOptions1);
// Monday, August 10, 2020

const dateOptions2 = {
  day: 'numeric',
  month: 'short'
};

console.log(date.toLocaleDateString('en-US, dateOptions2);
// Aug 10

const dateOptions3 = {
  month: 'long'
};

console.log(date.toLocaleDateString('fr-FR, dateOptions3);
// juillet
Enter fullscreen mode Exit fullscreen mode

Options

  • weekday: 'narrow', 'short', 'long'
  • day: 'numeric', '2-digit'
  • month: 'numeric', '2-digit', 'narrow', 'short', 'long'
  • year: 'numeric', '2-digit'

Date.prototype.toLocaleTimeString

Not only does this method support locale like the previous toLocaleDateString method, but it also supports a timeZone option.

Support

CanIUse Support

const date = new Date();

console.log(date.toLocaleTimeString('en-US'));
// 1:38:27 PM

const timeOptions1 = {
  hour12: true,
  hour: 'numeric',
  minute: '2-digit',
  second: '2-digit',
};

console.log(date.toLocaleTimeString('en-US', timeOptions1));
// 1:38:27 PM

const timeOptions2 = {
    timeZone: 'America/Los_Angeles',
};

console.log(date.toLocaleTimeString('en-US', timeOptions2));
// 10:38:27 AM
Enter fullscreen mode Exit fullscreen mode

Options

  • hour12: true, false
  • hour: 'numeric', '2-digit'
  • minute: 'numeric', '2-digit'
  • second: 'numeric', '2-digit'

Top comments (7)

Collapse
 
functional_js profile image
Functional Javascript

Nice tips Bob.

What would be your approach to getting this date format?...

[2020-08-31 Mon 13:54]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rfornal profile image
bob.ts

Generating something like that is outside the patterns used in the article. The date / time patterns used are for local-formatted dates and times.

Unfortunately, the date / time pattern you have would have to be generated via string formatting ... so, you's end up with something ugly like (only doing partial pattern) ...

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(`${curr_year}-${curr_month}-${curr_date}`);

... this is why tools such as moment.js are so popular. Although, saying this, I would look around at the various date / time tools. There have been several new ones and you might find a tool that does what you want with a smaller footprint.

Collapse
 
functional_js profile image
Functional Javascript • Edited

Thanks for looking into that Bob.
I figured since you're the date/time guru, you'd have a smoother answer than the func I use, which I wrote a while back. ;)

/**
@func util
add a leading zero, if the number is a single digit number
i.e. prefix with a zero, if under 10

@param {number} t - a time or date chunk, representing either the month, day-of-month, hour, minute, or second
@return {string}
*/
const add0 = t => t < 10 ? `0${t}` : String(t);
/**
@func
get the current time, in a canonical human-readable format:
"YYYY-MM-DD ddd HH:mm"

@cons
no seconds
no milliseconds

@return {string}
*/
export const getDateStandard = () => {
  const dt = new Date();
  const y = dt.getFullYear();
  const m = add0(dt.getMonth() + 1);
  const d = add0(dt.getDate()); //day of month
  const w = dt.toDateString().substring(0, 3); //day of week enum, either Mon, Tue, Wed, Thu, Fri, Sat, Sun
  const h = add0(dt.getHours());
  const min = add0(dt.getMinutes());
  return `[${y}-${m}-${d} ${w} ${h}:${min}]`;
};
//@tests
console.log(getDateStandard());
/*
output:
[2020-09-01 Tue 09:10]
*/
Thread Thread
 
rfornal profile image
bob.ts

Your solution is probably the clearest pattern. I was thinking about the toISOString and having an ability to pull out whole patterns, the problem is that is doesn't take into account the timezone offset.

Maybe something like this ...

const getDateStandard= () => {
  const d = new Date();
  let local = new Date(d);
  local.setMinutes(d.getMinutes() - d.getTimezoneOffset());

  const s_iso = local.toISOString();
  const date = s_iso.substring(0,10);
  const time = s_iso.substring(11,16);
  const dow = local.toDateString().substring(0, 3);

  return `[${date} ${dow} ${time}]`;
};

console.log(getDateStandard());
Thread Thread
 
functional_js profile image
Functional Javascript

That's a great one if one wants to timestamp in UTC time, or another timezone.
Thanks!

Collapse
 
rfornal profile image
bob.ts

In my research to answer this question, I did note that the .toISOString method (MDN HERE) has most of what you are looking for without the odd complexity of my first answer. Since the output pattern is fixed, you might be able to slice out the parts you want, get the Day of Week and reassemble it all quickly.

Collapse
 
ebrima2ray1 profile image
Ebrima Touray

Thanks for sharing! You help me a lot