How to format javascript date to am/pm, minutes, hours, days, months, moment.js etc

Author image
Author

Fashanu T.

05, Feb 2021

2 Minutes Read...


In this article, i will show you how to format javascript date, convert one date format to another and more:

  1. Unix to any JavaScript date format.
  2. Format JavaScript Date to Unix. 
  3. Format JavaScript date to local string (English, Korean, Hindi etc).
  4. Get milliseconds, seconds, minutes, hours, days, month etc from JavaScript Date format.
  5. Local language (en, ru, es... etc) readable format for javascript Date, i.e just now, last month, 2 minutes ago, 4 hours ago etc.  

With no further ado, lets get right to business —🍹.

1. How to Convert Unix time to JavaScript Date format

Unix is a 10 digit decimal of seconds, couting way back since 1970. To convert it to an acceptable javascript date format, we multiply the digit by 1000.

This converts it to milliseconds, which is a valid and acceptable parameter of the Date object in JavaScript. See the sample below:

javascript
var unixTime = 1589754240;
var unixToMilli = unixTime * 1000;
var validDate = new Date( unixToMilli );
console.log( validDate.toString() );

// Sun May 17 2020 23:24:00 GMT+0100 (West Africa Standard Time)

//Time zone varies

2. Convert JavaScript Date to Unix

To convert any Date format to Unix, you first need to convert the date object to milliseconds, then divided by 1000 to get the Unix time.

See the samples below:

javascript
var date = new Date(2012, 11, 20, 3, 0, 0);
var milli = date.getTime();
var unix = milli/1000;
console.log( unix );
// 1355968800

date = new Date('2021/12/14');
milli = date.getTime();
unix = milli/1000;
console.log( unix );
// 1639436400

3. Format JavaScript date to Local String

You can now format JavaScript Date to your local language i.e English, Russia, Korea, Japanese etc using Date.prototype.toLocaleDateString() method.

To do this, you must first supply a valid Date argument into the Date constructor, then use the toLocaleDateString() method from the Date class.

Lets check out the example below:

javascript
var recently = new Date(2012, 11, 20, 3, 0, 0);

console.log( recently.toLocaleDateString() );
// 12/20/2012

To format javascript date in other local language, add your local language short code as a parameter in the toLocalDateString() method like the sample below:

Check here for different language code, and this source as well.

javascript
var recently = new Date(2012, 11, 20, 3, 0, 0);

console.log( recently.toLocaleDateString('en-GB') );
// 12/20/2012

Mind you, toLocaleDateString() accepts two parameters. The local language and formatting options.

Using the local language parameter alone hardly changes anything.

To add more options, check the example below:

javascript
var recently = new Date(2012, 11, 20, 3, 0, 0);

var option = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }
console.log( recently.toLocaleDateString('en-GB', options) );
// Thursday, 20 December 2012

Here are some available options for use:

  1. weekday: long (e.g Thursday), short (e.g Thu), and narrow (e.g T).
  2. hour12: true (for 12 hour time), false (for 24 hour time).
  3. year: numeric (e.g 2021), 2-digit (e.g 21).
  4. month: numeric (e.g. 2), 2-digit (e.g 21), long (e.g March), short (e.g Mar), narrow (e.g M).
  5. day: numeric (e.g. 1), 2-digit (e.g 01).
  6. hour: numeric (e.g. 1), 2-digit (e.g 01).
  7. minute: numeric (e.g. 1), 2-digit (e.g 01).
  8. second: numeric (e.g. 1), 2-digit (e.g 01).
  9. timeZoneName: long (e.g West Africa Standard Time) , short (eg. GMT+0100 ).
  10. timeStyle: full, short, long, medium (hour, minute, am/pm..).
  11. dateStyle: full, short, long, medium (year, month, day etc.).

Apart from the toLocaleDateString() method, there is also an International Date time format method for formatting date.

Lets take a look at a couple of examples below:

javascript
var date = new Date(2020, 11, 20, 3, 23, 16, 738);

var intDate = new Intl.DateTimeFormat('en-US').format(date));
console.log ( intDate );
// 12/20/2020

var opt =  { timeStyle: 'long', dateStyle: 'full'  };
console.log ( new Intl.DateTimeFormat('en-GB', opt ).format(date) );
// Sunday, 20 December 2020 at 14:23:16 GMT+11


let o = new Intl.DateTimeFormat("en" , {
  timeStyle: "medium",
  dateStyle: "short"
});
console.log(o.format(Date.now())); 
// 07/07/20, 13:31:55 AM

4. Format date to milliseconds, seconds, minute, hours, am/pm, days, months and more..

To get JavaScript date format in minutes, hours etc, i will be using a utility function that returns all of the above at one go:

javascript
function time(...arg) {
  var date = new Date(arg);
  return {
    milliseconds: function() {
      return date.getMilliseconds();
    },
    seconds: function () {
    return date.getSeconds();
    },
    minutes() {
      return date.getMinutes();
    },
      hours() {
      let hours = date.getHours();
      let shortHours = hours % 12;
      shortHours = shortHours ? shortHours : 12;
      shortHours = shortHours < 10 ? '0' + shortHours : shortHours;
      return { long: function () { return hours; }, short: function () { return shortHours; } };
    },
       ampm() {
      let ampm = parseInt(this.hours().long()) >= 12 ? 'pm' : 'am';
      return ampm;
    },
    day() {
      return date.getDate();
    },
    month() {
      const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      return months[date.getMonth()];
    },
     year() {
      return date.getFullYear();
    }
  }
}

I think the time function from above is self explanatory. 

5. Format Date in human readable form like: just now, 2 years ago etc.

With the new introduction of internalization, what you normally do with moment.js that requires tons of files and code to work can be done with only a few lines of code, and much faster too.

Quickly format date in readable forms like:

  1. just now
  2. in 2 weeks
  3. last year
  4. 2 minutes ago
  5. 2 days ago (and more...)

I created a package with its tutorial to do this.

You can simply copy or install to use this package in your project on github.

The most interesting aspect of it all is the fact that its barely 30 lines of code and the source file is easy to understand.

SO, you can enhance it or get started with using moment/timeAgo in your project by scanning through the source file of the project

More read:

  1. How to write, test, host and publish JavaScript package to GitHub, NPM & jsDelivr.
  2. All about JavaScript spread operator and accepting any number of argument in a function.
  3. How to create moment.js or use time ago localized date format in JavaScript from scratch.
  4. Most important JavaScript string methods you should know.
  5. Javascript closure in 3 minutes: examples and interview questions.
  6. JavaScript redirect, open new tab redirect without Popup block.
  7. How to send JSON string using AJAX, fetchAPI to php and dealing with 403 error while using AJAX.
  8. Using JavaScript fileReader in converting files to different formats and uses of fileReader.
  9. How to get a free SSL certificate and configure it on your website.
  10. Top 4 free web hosting with domain to consider today.
  11. How to add google maps to website: route, search, street view image, markers, geolocation.