Home » JavaScript » Javascript Date Format Example

About Era Balliu

Era Balliu
Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.

Javascript Date Format Example

As different countries use different date formats, the need to format them differently now has a solution in almost all programming languages and frameworks. Some of them use special functions, some others use dedicated libraries, and some just leave you to their syntax and your imagination.

Let’s see what JavaScript provides for those of us in dire need to format dates.

JavaScript Interview Coming Up?

Subscribe to our newsletter and download the Ultimate JavaScript interview questions and answers collection right now!

In order to get you prepared for your next JavaScript interview, we have compiled a huge list of relevant questions and their respective answers. Besides studying them online you may download the eBook in PDF format!

 

Date objects

Date objects are based on the number of milliseconds since January 1,1970 UTC. They have no syntax, but are stated using constructors, like below:

new Date(); 
new Date(value); 
new Date(dateString); 
new Date(year, month[, day[, hour[, minute[, second[, millisecond]]]]]);

You can use them like this:

var today = new Date();
var birthday = new Date('November 16, 1994 01:00:00');
var birthday = new Date('1994-11-16T01:00:00');
var birthday = new Date(1994, 11, 16);
var birthday = new Date(1994, 11, 16, 1, 0, 0);

Be careful when invoking the Date object, because if you use it without the new operator, it will only return the current date and time as a string.

The Date object has a number of specific qualities to it’s name, for example, if you give it an illogical value, say 3/14/2013, it transforms it into 3/2/2014. If you don’t provide a time and date, the constructor will fill it in with the systems time and date, and if two arguments are supplied, the other ones will be set to 0. JavaScript supports a number of universal formats, and even local equivalents of it, which provides consistency and uniform behavior across platforms.

Date.prototype
Date.prototype allows you to add properties to the Date object. It is used together with the methods, which are divided into getters, setters and conversion getters, but we’ll discus them shortly. The properties inherited from the function are: arity, caller, constructor, length and name.

Methods

The three methods used with the Date object are Date.now(),Date.parse() and Date.UTC().

  • Date.now() returns the current time of the system.
  • Date.parse() parses a string representation of a date and returns the numeric value corresponding it.
  • Date.UTC() returns the number of milliseconds since January 1,1970.

Also there are these methods inherited from the function: apply, call, toSource and toString.

Date instances

The methods that Date instances inherit from Date.prototype can be divided into three big groups:Getters, Setters and Conversion getters.

    • Getters

We use Getters as Date.prototype.getDay, where you can put Date, Month, Year, Milliseconds and other ones which you can find here, instead of Day.

    • Setters

We use Setters in a similar way: Date.prototype.setMonth. You can find the list on what exactly you can set, here.

    • Conversion getters

And finally, we use Conversion getters to get and convert dates at the same time. It is used like this: Date.prototype.toISOString(), and you can find a whole list on what you can convert here.

Calculating elapsed time

By using Date objects you can calculate how much time has passed since you last did something, like this:

var start = Date.now();

randomfunction();
var end = Date.now();
var elapsed = end - start; 

You get the time in a specific moment, then do something for some time, and then get the time after you finish. You get the difference and that is the elapsed time in milliseconds.

JavaScript Libraries

There are lots of JavaScript libraries dedicated to data formatting. Two of the most efficient are Datejs and Moment.js, both open source and released under the MIT license. We’ll see how they work.

Datejs
You can download Datejs here, and then script it in you main file. It gives you the possibility to format you dates according to where you live, giving you more than 150 options. To do that you just swap the date.js file for a culture specific one, like below:

<!--Swap this file for the one you need, example for german and french below-->
<script type="text/javascript" src="date.js"></script>

<!-- German-->
<script type="text/javascript" src="date-de-DE.js"></script>

<!-- French -->
<script type="text/javascript" src="date-fr-FR.js"></script>

Let’s get our hands on it. Want to know what’s the date today? Write this code:

Date.today();

Or what will be the day ten days from now?

Date.today().add(10).days();

If you wanna know what the date will be this Friday, you write this:

Date.friday();

You can even ask if Friday is today, doing this:

Date.today().is().friday();

And in case it returns false (it can even return true), you can ask what day it is like so:

Date.today().getDayName();

You can even get the first Monday or last Sunday of the year by writing this:

Date.january().first().monday();

Date.dec().final().sunday();

Included with the Date.js library is a really good replacement for JavaScript Date parse. Take a look at the code:

Date.parse('today');

Date.parse('tomorrow');

Date.parse('July 8');

Date.parse('July 8th, 2007');

Date.parse('July 8th, 2007, 10:30 PM');

We have parsed the date of today, tomorrow, July 8th, July 8th of 2007 and July 8th of 2007 at 10:30 PM, just by using the Date.parse(); function.

Moment.js

Moment.js is created to parse, validate, manipulate and display dates in JavaScript. It is designed to work both in the browser and Node.js. You can install it through Bower, npm or NuGet.You can format dates like this:

moment().format('MMMM Do YYYY, h:mm:ss a'); // December 7th 2014, 6:17:51 pm
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Dec 7th 14
moment().format('YYYY [escaped] YYYY');     // 2014 escaped 2014                     
moment().format();                          // 2014-12-07T18:18:11+01:00

You can get a relative time, like this:

moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 2 years ago
moment().startOf('day').fromNow();        // 18 hours ago
moment().endOf('day').fromNow();          // in 6 hours
moment().startOf('hour').fromNow();      //20 minutes ago

And it even provides you multiple locale support:

moment().format('L');    // 07/12/2014
moment().format('l');    // 7/12/2014
moment().format('LL');   // 7 Dhjetor 2014
moment().format('ll');   // 7 Dhj 2014
moment().format('LLL');  // 7 Dhjetor 2014 18:21
moment().format('lll');  // 7 Dhj 2014 18:21
moment().format('LLLL'); // E Diel, 7 Dhjetor 2014 18:21
moment().format('llll'); // Die, 7 Dhj 2014 18:22

Later.js
Later.js is a library that triggers recurring events, and defines complex schedules. It can even use user-friendly expressions such as “every 10 seconds”. You can install it through npm:

$ npm install later

Or even using Bower:

$ bower install later

You can define a schedule by text, recursion or manually like below:

var textSched = later.parse.text('at 10:15am every weekday');
var recurSched = later.parse.recur().last().dayOfMonth();
var manualSched = {schedules: [{M: 3, D: 21}]};

Still you can define more complex schedules like this one, who fires the weekday closest to the 15th of every month except March. Here’s the code:

var complexSched = later.parse.recur()
                  .on(15).dayOfMonth().onWeekday().on(2).hour()
                .and()
                  .on(14).dayOfMonth().on(6).dayOfWeek().on(2).hour()
                .and()
                  .on(16).dayOfMonth().on(2).dayOfWeek().on(2).hour()
                .except()
                  .on(3).month();

You can even configure your timezone, either in UTC format or in local time. You configure it in UTC like this:

later.date.UTC();

And you can turn it to local time like this:

later.date.localTime();

With Library.js you can even calculate future or past occurrences once you set a recurring schedule. Look at the code snippet below:

var recurSched = later.parse.recur().last().dayOfMonth();
      next = later.schedule(recurSched).next(10);

Also a lot of other functions of this library are available, and you can take a look at it’s documentation on Github or even modify it yourself as it’s open-source.

Download the source code

This was an example of JavaScript date format.

Download
You can download the full source code of this example here : DateFormat

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook