Formatting Date in JavaScript

You can use built-in JavaScript object Date to do the date formatting in JS, you can also use Locales to format your date. I want to show date in mm/dd/yyyy hh:mm Z, I used simple trick, the format I am expecting is US format, and JS frovides API to convert Date to specific local, so I passed en-US as local parameter, and using options to get the desired output.

few of the options to instantiate Date

var today = new Date(); 
var myDate = new Date(dateString);

where dateString is string representing an RFC2822 or ISO 8601 date format e.g. 12/21/2014 00:00 GMT+5:30

Converting to Local

    var myDate = new Date();
    var options = { timeZoneName: 'short', hour : '2-digit', minute : "2-digit", hour12: false};
    var dateStr = myDate.toLocaleString('en-US', options);

In options, I specified the timeZoneName which specifies if we want a short timezone name or long, hours, minutes and hour12 which specifies if the time needs to be shown in 12 hour format of 24 hours.

Other available options

  • weekday : [“narrow” | “short” | “long”]
  • era: [“narrow” | “short” | “long”]
  • year : [“2-digit” | “numeric”]
  • month : [“2-digit” | “numeric” | “narrow” | “short” | “long”]
  • day : [“2-digit” | “numeric”]
  • hour : [“2-digit” | “numeric”]
  • minute : [“2-digit” | “numeric”]
  • second : [“2-digit” | “numeric”]
  • timeZoneName : [“short” | “long”]

And if you need to format Date to more specific date format, then can use JS Date provided methods to get specific date elements like, day, year, month time etc.

   function padZero(dateArg) {
      if (dateArg < 10) {
        return '0' + dateArg;
      }
      return dateArg;
   }
   
  function formateDate(date) {
    return date.getUTCFullYear() +
        '-' + padZero(date.getUTCMonth() + 1) +
        '-' + padZero(date.getUTCDate()) +
        ' ' + padZero(date.getUTCHours()) +
        ':' + padZero(date.getUTCMinutes()) +
        ':' + padZero(date.getUTCSeconds()) ;
  }

JSFiddle Code link

Advertisements
Formatting Date in JavaScript

One thought on “Formatting Date in JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s