JavaScript Date Object

Javascript: Things you should know

Note: This is part IV of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. This section goes over the creation of date objects. Most resources go over creating a current time date object. This goes over the rest. The previous entry was JavaScript Objects. The next entry list all the date object methods. Please let me know what you think and it there is anything I am missing. Enjoy.

Creating JavaScript Date Objects:

There are fours ways of instantiating a date object:

  1. Without parameters
    Returns the users current date based on client computer’s clock.

    new Date();

    Example:
    var currentTime = new Date();

  2. With a numeric parameter:
    Returns the date measured from midnight January 1, 1970 (+/- GMT diff) plus the time in milliseconds that was passed as the parameter

    new Date(milliseconds);

    Examples:
    var startTime = new Date(0); // Returns
    your time when GMT hit the new year.
    var millenium = new Date ((365*30 + 7)*24*60*60*1000); // returns the millenium at GMT, The +7 is for the leap days.

  3. With a string parameter:
    The string parameter must be a date correctly formatted in string format. The Date object only seems to accept 1 date string format, which is provided in the examples below. The flexibility is only in the day: the number may include a leading zero, but it is not required.

    new Date(dateString)

    Examples:
    var auntsBirthday = new Date("September 4, 1902") // She’s 105
    var modifiedTime = new Date("July 27, 2005 12:22:00") // format must be exact

  4. With an array of parameters:
    Pass the different date element parameters in the order above. If you don’t specify all the parameters, or a parameter is non-numeric, 0 is passed. If your value is numeric, but not a valid value (such as hours == 25) no error will be thrown, though it may be a logic error. The most common error is the month parameter: remember that the arrays start at index of 0, so January is 0 and December is 11.

    new Date(year, month, day, hours, minutes, seconds, milliseconds)

    var modifiedTime = new Date(2007,7,27)
    var modifiedTime = new Date(2007,7,27,13,22,0)

Here are a few examples and what gets returned (javascript must be enabled):

  • currentTime = new Date()
  • timeBasis = new Date(0)
  • lastYear= new Date(-365*24*60*60*1000)

  • var currentTime = new Date("November 4, 2008");

  • anniversary = new Date(2003,8,21)
  • exactTime = new Date(1969,0,3,16,4,12,500)

Note:

  • new Date(0) will not return midnight of January first unless your computer set to GMT.

Common JavaScript Date Object Errors

  • new date()
    //Error: Date is case sensitive
  • new Date("412")
    //
    Error: No data conversion
  • new Date("June 31, 2005 29:95:73 ")
    //Logic Error: Too many hours in your day, and there are only 30 days in June.
    Returns July 2, 2005; which is unlikely your intention.
  • new Date("July 27, 2005 12:22pm")
    // invalid date error – doesn’t understand PM
  • new Date("2007-7-27")
    //Invalid Date: – string in wrong format**
  • new Date(1969,12,3,16,4)
    //Returns January 3, 1970 instead of December 3, 1969. Logic Error: monthArray is 0 – 11.

Notes:

  • When passing the month as a number, remember that the array starts at 0. Optional values are 0-11. Javascript will not throw an error, but there will be a logic error.
  • The date string must be of the correct fomat. The minimum is "Month dd, yyyy", to "Month dd, yyyy hh:mm:ss". The Month doesn’t seem to be case sensitive in my tests, but I haven’t checked all browsers. Good coding practices dictate that it should be capitalized. .
  • JavaScript uses the date of midnight, January 1, 1970 UTC as a starting point for all of its calculations.

An Example of Converting a PHP/Unix date to a usable JavaScript date:

So my quandry was that the date I received was written in an unusable format: The date the server sent was similar to 2007-07-22T22:57:35Z – yyyy-mm-ddThh:mm:ssZ, which is the date in ISO 8601 format (see converting ISO 8601 dates in PHP for a completely different take on conversion). I had to convert an ISO 8601 date to a parameter I could use in the Date object constructor

My first thought was to replace the T and Z with spaces, 2007-07-22 22:57:35 , which looks correct, but isn’t.
As we learned above (see Date error example above), date strings much be in the "Month dd, yyyy" format. The yyyy-mm-dd format will not work.

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = new Date(myStringDate.replace(/\D/g, " ")) //returns "invalid date".

My second thought was to split the string into parameters.

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = myStringDate.replace(/\D/g, " ");
var dObj = myStringDate.split(" ");       
          //array is (2007, 07, 22, 22, 57, 35) 
var myDate = new Date(dObj[0], dObj[1], dObj[2], 
           dObj[3], dObj[4], dObj[5]);

That works, but gives me the wrong date. We have a logic error. The month array starts at 0. month[07] is August, not July. The solution was to subtract 1 from the 2nd parameter

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = myStringDate.replace(/\D/g, " ");
var dObj = myStringDate.split(" ");
var myDate = new Date(dObj[0], (dObj[1]-1), dObj[2], dObj[3], dObj[4], dObj[5]);
document.write("Making a date from a string: " + myDate);



Writing Pretty Dates

Javascript 1.2 gave us some prettier ways of writing out dates. Still, you might not find the format you need with the methods provided. Here are some arrays that you should feel free to cut and paste into your code.

dyOfWeek = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
daysOfWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday", 
             "Thursday", "Friday", "Saturday");
monOfYear = new Array("Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.",
             "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."); 
monthsOfYear = new Array("January", "February", "March", "April", "May", 
    "June", "July", "August", "September", "October", "November", "December"); 

toLocaleDateString() works for much of what I need. But, sometimes you need something a little different. You can either edit using regular expressions, or you can create a pretty date from scratch.

Here are some formats and how to create them. I will use the date we created, the methods described above and the 4 arrays posted here.

(myTime.getMonth() + 1) + "/" + myTime.getDate() + "/" + myTime.getFullYear()
var hours =  myTime.getHours();
var ampm = (hours > 11)? "PM" : "AM";
hours = hours%12;
hours = (hours == 0)? 12 : hours;
time = hours + ":" + myTime.getMinutes() + " " + ampm;
July 2007
monthsOfYear[myTime.getMonth()] + " " + myTime.getFullYear()

Formatting Javascript Dates:

Want to extend the Date object to be nicely formated? Gavin Kistner did the work for us. Extending the Date Object which creates the a custormFormat for the date object. To use this prototype, include the function in your javascript, and call it this way:

var prettyDate = myDate.customFormat('#DDDD#, #MMM# #D#, #YYYY#'); 
var prettyTime = myDate.customFormat('#h#:#mm##ampm#');

Here’s the code:

Date.prototype.customFormat=function(formatString){ 
    var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhh,hh,h,mm,m,ss,s,ampm,dMod,th;
    YY = ((YYYY=this.getFullYear())+"").substr(2,2);
    MM = (M=this.getMonth()+1)<10?('0'+M):M;
    MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substr(0,3);
    DD = (D=this.getDate())<10?('0'+D):D;
    DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substr(0,3);
    th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
    formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
     h=(hhh=this.getHours());
    if (h==0) h=24;
    if (h>12) h-=12;
    hh = h<10?('0'+h):h;
    ampm=hhh<12?'am':'pm';
    mm=(m=this.getMinutes())<10?('0'+m):m;
    ss=(s=this.getSeconds())<10?('0'+s):s;
    return formatString.replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm);
	 } 
This entry was posted in JavaScript, PHP, Web Development. Bookmark the permalink.

3 Responses to JavaScript Date Object

  1. Estelle says:

    This entry was getting a bit long, so i cut out the “methods and properties of the date object.” I am finishing it up and should post it in the next few days.

  2. Estelle says:

    Examples of JavaScript Date object methods are now posted at http://www.evotech.net/blog/2007/09/javascript-date-object-methods/

  3. Hey Estelle,
    Thanks for sharing as I learnt a few things regarding the Javascript Date() object. I’m currently writing a small date validation function and your post came in handy.

    Keep up the top effort.

    Later…
    George G.

Leave a Reply

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