Common JavaScript Date Operations

Here are some JavaScript’s most common date operations which you may require during your project.

MySQL Timestamp to Date

function parseMySqlDate( dateStr ) {
   return new Date( dateStr.replace( /-/g, '/' ) );

MySQL date contain dashes in it (e.g. 2012-01-16) so first replace them with forward slashes because MySQL date is not directly recognizable in JavaScript. /-/g is the regular expression which searches for – (dash) in dateStr. Alphabet g in regular expression means global which is used to search the whole string, not just the first character found. For example is our timestamp is “2012-01-16 15:30:00″. It will become “2012/01/16 15:30:00″ and passed to Date constructor which will directly parse it and convert it to Date object.

Date to MySQL Timestamp

function dateToMySqlTimestamp( dateObj ) {
   return dateObj.getFullYear() + "-"
        + ( dateObj.getMonth() + 1 ) + "-"
        + dateObj.getDate() + " "
        + dateObj.getHours() + ":"
        + dateObj.getMinutes() + ":"
        + dateObj.getSeconds();

In JavaScript month starts from 0 to 11. So I incremented month by one to get range 1 to 12.

Comparing Dates

You can compare date objects directly using relational operators.

//defining two equal date objects
var dateObj1 = new Date( '2012/04/15 18:00:00' );
var dateObj2 = new Date( '2012/04/15 18:00:00' );
dateObj1 < dateObj2 //false
dateObj1 > dateObj2 //false
dateObj1 <= dateObj2 //true
dateObj1 >= dateObj2 //true
dateObj1 == dateObj2 //false
dateObj1 === dateObj2 //false

As you can see from the above examples, all operators are working fine except for the equality (==) and identity (===) operators. These two operators always return false even if both operands are equal. To fix this issue, convert both Date objects time to milliseconds using getTime() method and then compare it.

dateObj1.getTime() == dateObj2.getTime() //true
dateObj1.getTime() === dateObj2.getTime() //true

Calculating Difference Between Dates

As explained above, someDateObj.getTime() method returns time in milliseconds relative to January 1, 1970, 00:00:00 UTC. So we can calculate difference between two Date objects using milliseconds. Following example gets the difference between two Date objects in hours.

//defining two date objects with 2 hours difference
var dateObj1 = new Date( '2012/04/15 16:00:00' );
var dateObj2 = new Date( '2012/04/15 18:00:00' );
//get difference in milliseconds
var diffMilliseconds = dateObj1.getTime() - dateObj2.getTime();
//make the difference positive
if( diffMilliseconds < 0 ) diffMilliseconds *= -1;
//convert milliseconds to hours
var diffHours = ( diffMilliseconds / 1000 ) / 60 / 60;
//print on console
console.log( diffHours + " hour(s)" );

Cloning Date Object

Check the second Date constructor in MDN’s Date Reference. It takes milliseconds as an argument.

new Date(milliseconds)

We can get milliseconds of any Date object using getTime() or valueOf() methods and pass it to Date constructor to create exact clone of it.

var dateObj1 = new Date( '2012/04/15 16:00:00' );
//clone using getTime()
var clone1 = new Date( dateObj1.getTime() );
//clone using valueOf()
var clone2 = new Date( dateObj1.valueOf() );

Getting Month Name/Abbreviation

Update: Added on 30th April, 2012

There’s no method in JavaScript Date object that returns month name or abbreviation of it. But it’s not difficult to get then month name/abbreviation.

//create an array with month names
var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
//create an array with month abbreviations
var abbr = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var d1 = new Date();
console.log( months[ d1.getMonth() ] ); //will print month name
console.log( abbr[ d1.getMonth() ] ); //will print month abbreviation

All you have to do is make use of an array to get month name. Remember getMonth method returns month from 0 to 11 so simply place it in place of index of an array and get month name/abbreviation.

JavaScript Date References

comments powered by Disqus