Speed dating - The Art of the JavaScript Date Object
Written by Ian Elliot   
Thursday, 15 June 2017
Article Index
Speed dating - The Art of the JavaScript Date Object
Date and times as strings



Date and times as strings

Of course one of the common tasks is to present a date or a time or a date and time to a user as a formatted string. This is easy in JavaScript because you can use a range of built in methods.

The most basic of these is the toString method which returns a string showing the date and local time with the correction applied to the UTC value:

Mon Sep 5 13:10:30 UTC+0100 2011

This is complete but often more than is required by an innocent user who has no idea what UTC is!

A more user friendly version of this method is the toLocaleString method which shows the local time and date in the local format without any UTC information:

05 September 13:10:30

Of course if you want the UTC date and time then you can use the toUTCString method

Mon, 5 Sep 13:10:30 UTC

If you just want the date and not the time then you can use the toDateString method or the toLocaleDateString method which returns the date formatted in the local style:

Mon Sep 5 2011


05 September 2011

Similarly if you only want the time part of the date and time you can use the toTimeString method which returns a local time with an indication of the UTC correction applied or the toLocaleTimeString which returns the local time without a mention of UTC:

13:10:30 UTC+0100



The one that is missing is a method to return a UTC time but this isn't a big loss and it can be made up for very easily.

Extending date formats

What do you do if you want a date or time in a different format?

You have two possible solutions.

You could use the raw date and time access methods such as getHours and put together the date and time format you want. It also makes sense to extend the methods of the Date instances by adding methods to the prototype. For example to construct the day name followed by the day number you could write:

 var day=new Array("Sun","Mon","Tue","Wed",
 return day.toString()+" "+this.getDate();

and then write:

var t=new Date();

to display Mon 5.

The alternative way is to take the existing string methods and process their results. For example the toString method has all of the information we need to implement the toDayDate method by extracting the information from a string something like:

Mon Sep 5 13:10:30 UTC+0100 2011

So all we need are the first three characters and the two starting at the eighth:

  return this.toString().slice(0,3)+" "+

This works just as well as the previous method.

It is up to you which you choose.

Date arithmetic

Now we come to perhaps the most confusing part of using the Date object - date arithmetic.

Let's consider a particular problem.

You want to add one day to today's date and time to get the date and time of tomorrow.

To solve this problem you have to remember that the Date object stores the number of milliseconds from the fixed date. So to add one day you have to add one day's worth of milliseconds i.e. 24*60*60*1000.

However if you try:

var t=new Date();

you will discover that the result is the date string with the result of the calculation concatenated on the end. Of course when you use a Date object in an expression either the toString or toValue method is called to provide a default string or numeric value. In this case the toString method is called and the expression is interpreted as a string operation. If you want to know more about default values see - Objects with values.

There are two ways around this problem The first is to force JavaScript to convert the Date to a numeric value i.e. to call toValue. For example:

var t=new Date();

This works because 1*t has to be a number however this isn't a good way to express the idea. Much better is to use the getTime method which returns the number of milliseconds as a numeric value. However if you try:

var t=new Date();
var t2=t.getTime()+24*60*60*1000;

You will find that instead seeing a date string as the result you see a numeric value. This is perfectly reasonable, after all you converted t to a numeric value and then added something to it. The result is that t2 is numeric and not a Date object.

To get the result as a Date object you have to make a new one based on the number of millisecond ticks:

var t=new Date();
var t2=new Date(t.getTime()+24*60*60*1000);

This now works and we have a pattern for how to do date/time arithmetic in JavaScript.

  1. do all date/time arithmetic in milliseconds from the fixed date by converting any Date objects to their millisecond tick value.

  2. Convert the final millisecond tick value back to a Date object if this is what is required.

The only problem with this is that it would be nice to have a general way of working out the millisecond tick value of an arbitrary date or time interval, e.g. one hour, ten days, three minutes and so on.

One way of doing this is to construct a Date object with that number of millisecond ticks away from the fixed date. For example, a Date object that has one hour's worth of milliseconds can be created using:

var hour=new Date(1970,0,1,1);

similarly one minute is:

var minute=new Date(1970,0,1,0,1);

and one second:

var second=new Date(1970,0,1,0,0,1);

a day is just:

var day=new Date(1970,0,2);

i.e. one day away from the fixed date.

Once you have these intervals you can do date/time arithmetic very easily by using the getTime method to convert to milliseconds and constructing a new Date object when you need to. For example:

var t=new Date();
var hour=new Date(1970,0,1,1);
var t2=new Date(t.getTime()+hour.getTime());

You now should be able to see how to generalize this to any date/time arithmetic you need to perform. There is more about date and time arithmetic in the next two chapters.

Of course you could add extension methods to the Date object to provide a more regular way of doing date/time arithmetic but there are advantages to adding your own TimeInterval object type that has these extra methods and doesn't modify the built-in object. In fact this is always a better idea than extending the built-in objects and this is exactly what the next chapter is all about.





JavaScript Data Structures 



  1. The Associative Array
  2. The String Object
  3. The Array object
  4. Speed dating - the art of the JavaScript Date object
  5. Doing JavaScript Date Calculations
  6. A Time Interval Object
  7. Collection Object
  8. Stacks, Queue & Deque
  9. The Linked List
  10. A Lisp-like list
  11. The Binary Tree
  12. Bit manipulation
  13. Typed Arrays I
  14. Typed Arrays II
  15. Master JavaScript Regular Expressions
    * First Draft

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.


JavaScript Jems - Objects Are Anonymous Singletons

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, every object can be regard [ ... ]

JavaScript Canvas - Typed Arrays

Working with lower level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data.

Other Articles

raspberry pi books



or email your comment to: comments@i-programmer.info









Last Updated ( Thursday, 15 June 2017 )