Rune Grønkjærs Blog
Abonnér på mit feed

Javascript Date extension

The javaScript Date object is probably the hardest object to use, as it seems very complicated to the uninitiated. Very often I have needed to abstract from the complexity of the javascript Date object. I have written some extension methods to the Date object that can be very handy in many diferent situations. For a complete reference of all the javascript Date objects methods follow this link to w3schools.

.getWeekNumber()

Week number is not something used in many other countries than Denmark. Therefore the fewest programming languages support week numbers by default. One of them is javacsript. The getWeekNumber method calculates the week numbers.
Date.prototype.getWeekNumber = function() {
  var date = this;
  date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  var IsoDayOfWeek = date.getDay() == 0 ? 7 : date.getDay(); // Sunday = 7
  date.setDate(date.getDate() + 4 - IsoDayOfWeek); // Change to nearest thursday
  var DayOfYear = (date.getTime() - Date.UTC(date.getFullYear(), 0, 1)) / 864e5;
  var week = Math.floor(DayOfYear / 7) + 1;
  return week;
};

//getWeekNumber example
var date = new Date();
jQuery("#UgeTest").html("The number of this week: " + date.getWeekNumber());

The result:

.getDayName()

The name of the Weekday is very useful when working with weeks. My getDayName method returns just this and also supports various languages.
Date.prototype.getDayName = function(language) {
  var days = [], supportetLanguages = ["da-DK", "en-US"];
  /*
  Danish is the standard
  Note that this line uses a containsmetode from the Array object, 
  which are not in the native code of javascript.
  See my post about extending the array object for more information.
  */
  language = language && supportetLanguages.contains(language) ? language : "da-DK";
  
  //danish
  days["da-DK"] = [];
  days["da-DK"][0] = "Søndag";
  days["da-DK"][1] = "Mandag";
  days["da-DK"][2] = "Tirsdag";
  days["da-DK"][3] = "Onsdag";
  days["da-DK"][4] = "Torsdag";
  days["da-DK"][5] = "Fredag";
  days["da-DK"][6] = "Lørdag";
  //English
  days["en-US"] = [];
  days["en-US"][0] = "Sunday";
  days["en-US"][1] = "Monday";
  days["en-US"][2] = "Tuesday";
  days["en-US"][3] = "Wedensday";
  days["en-US"][4] = "Thursday";
  days["en-US"][5] = "Friday";
  days["en-US"][6] = "Saturday";

  return days[language][this.getDay()];
};

//getDayName example
var date = new Date();
jQuery("#UgedagTest").html(date.getDayName("en-US"));

The result:

.getMonthName()

As well as weekday names can be super handy, so can the month names.
Date.prototype.getMonthName = function(language) {
  var months = [], supportetLanguages = ["da-DK", "en-US"];

  /*
  Danish is the standard
  Note that this line uses a containsmetode from the Array object, 
  which are not in the native code of javascript.
  See my post about extending the array object for more information.
  */
  language = language && supportetLanguages.contains(language) ? language : "da-DK";

  //Dansk
  months["da-DK"] = [];
  months["da-DK"][0] = "Januar";
  months["da-DK"][1] = "Februar";
  months["da-DK"][2] = "Marts";
  months["da-DK"][3] = "April";
  months["da-DK"][4] = "Maj";
  months["da-DK"][5] = "Juni";
  months["da-DK"][6] = "Juli";
  months["da-DK"][7] = "August";
  months["da-DK"][8] = "September";
  months["da-DK"][9] = "Oktober";
  months["da-DK"][10] = "November";
  months["da-DK"][11] = "December";
  //Engelsk
  months["en-US"] = [];
  months["en-US"][0] = "January";
  months["en-US"][1] = "February";
  months["en-US"][2] = "March";
  months["en-US"][3] = "April";
  months["en-US"][4] = "May";
  months["en-US"][5] = "June";
  months["en-US"][6] = "Juli";
  months["en-US"][7] = "August";
  months["en-US"][8] = "September";
  months["en-US"][9] = "Oktober";
  months["en-US"][10] = "November";
  months["en-US"][11] = "December";
  return months[language][this.getMonth()];
};

//getMonthName example
var date = new Date();
jQuery("#MaanedNavnTest").html(date.getMonthName("en-US"));

The result:

.format()

The javascript Date object misses a true format method. I have been looking for an extension, which can format a date in all possible formats. I found what I was looking at Steven Levithans blog , where you can download the code.
Steven Levithans extension to the Date object is pretty wild. One can use all of the usual date formatting codes. Just look at the examples below.
var now = new Date();
var testTxt = "";
testTxt += '<br /><br />now.format("m/dd/yy"):<br />' + now.format("m/dd/yy");

//Can also be used as an independent method
testTxt += '<br /><br />dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT")<br />' + dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

// You can use one of several named stitches
testTxt += '<br /><br />now.format("isoDateTime")<br />' + now.format("isoDateTime");

// ...or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
testTxt += '<br /><br />now.format("hammerTime")<br />' + now.format("hammerTime");

//When using the independent dateFormat method
//You can send a date as a string 
smarttestTxt += '<br /><br />dateFormat("Jun 9 2007", "fullDate")<br />' + dateFormat("Jun 9 2007", "fullDate");

// Note that if you do not include a mask, as parameter
// dateFormat.masks.default will be used
testTxt += '<br /><br />now.format()<br />' + now.format();

// And if you do not include a date as parameter
// today will be used
testTxt += '<br /><br />dateFormat()<br />' + dateFormat();

// You can also skip the date object (as long as your mesh is not
// containing integers). In this case today will be used as well.
testTxt += '<br /><br />dateFormat("longTime")<br />' + dateFormat("longTime");

// You can convert a local time to UTC time. To do this
// you pass along true as a parameter (here it is not permissible to skip over parameters):
dateFormat(now, "longTime", true);
testTxt += '<br /><br />now.format("longTime", true)<br />' + now.format("longTime", true);

// ...Or you can prefix UTC to your mask
testTxt += '<br /><br />now.format("UTC:h:MM:ss TT Z")<br />' + now.format("UTC:h:MM:ss TT Z");
jQuery("#StevenLevithan").html(testTxt);

The result:

This post was written in Date, Extension, Javascript, regexp. Ad permalink to favorites. Follow all comments with RSS feed for this posts. Drop a comment or a trackback: Trackback URL. | Læs denne side på dansk dansk version

Drop a comment

Your email is never published nor shared. Required fields are marked *

*
*

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Dansk version