Speed dating - the art of the JavaScript Date object
Written by Ian Elliot   
Monday, 05 September 2011
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

or

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

or

13:10:30

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:

Date.prototype.toDayDate=function(){
 var day=new Array("Sun","Mon",
"Tue","Wed","Thu","Fri","Sat");
 day=day[this.getDay()];
 return day.toString()+" "+this.getDate();
}

and then write:

var t=new Date();
alert(t.toDayDate());

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:

Date.prototype.toDayDate=function(){
  return this.toString().slice(0,3)+" "+
this.toString().slice(8,10);
}

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();
t=t+24*60*60*1000;
alert(t);

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();
t=1*t+24*60*60*1000;

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;
alert(t2);

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);
alert(t2);

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());
alert(t2);

You now should be able to see how to generalize this to any date/time arithmetic you need to perform.

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.

If you would like to know how to do this look out for our forthcoming article on building an interval object.

 

If you would like to be informed about new articles on I Programmer follow us on Twitter or Facebook or you can subscribe to our weekly newsletter.

 

Related Articles

Date Hacks - Doing JavaScript Date Calculations

A JavaScript TimeInterval object        

Dates Are Difficult          

The Mod function       

JavaScript Bit Manipulation 

Cartoon - Why 1970? or Dating Troubles     

 

See Also:

Banner


Just JavaScript - Object Construction

Object creation is fundamental to all object-oriented languages, but in JavaScript is is left to the programmer to work out how best to do it and often the practice that you encounter isn't the best b [ ... ]



Just JavaScript - The Object Expression

As in most programming languages the expression is an important part of JavaScript, but it isn't quite the same. This is where the idea that JavaScript has some weird type conversions arises. But Java [ ... ]


Other Articles

<ASIN:0137054890>

<ASIN:0596517742>

<ASIN:1590597273>

 

 



Last Updated ( Tuesday, 10 September 2013 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.