Getting Started With Datejs

November 27th, 2007 | Tutorial

Welcome grasshopper. Let us begin.

Step #1 - Pick your weapon

In order to move safely through the shadowy world of the JavaScript Date Class you must add the date.js file to your arsenal of tools.

Example

<script type="text/javascript" src="date.js"></script>

You can download the latest release from datejs.com/download/ or connect directly to the SVN source repository via datejs.com/svn/.

The date.js file can be found within the /build/ folder.

Datejs has traveled to many lands and returns with knowledge of over 150 individual Cultures. Supporting your language of choice is simple, just swap out the date.js file for another culture-specific file.

Example

en-US [English (United States)]
<script type="text/javascript" src="date.js"></script>

en-US [English (United States)]
<script type="text/javascript" src="date-en-US.js"></script>

de-DE [German (Germany)]
<script type="text/javascript" src="date-de-DE.js"></script>

fr-FR [French (France)]
<script type="text/javascript" src="date-fr-FR.js"></script>

All 150+ CultureInfo files have been pre-compiled and are available within the same /build/ folder as date.js. Each culture file includes translations for many of the strings used in the Datejs library. Some strings have not been translated, although will be filled in over time as the community contributes.

Step #2 - Start your training

The Datejs library includes many helpful functions for easing the pain of developing with Dates and Times in JavaScript. Once the date.js file has been included into your page you can begin some serious training.

If you have not already done so, we highly recommend installing FireBug for FireFox. Among many things, Firebug allows you to execute custom JavaScript code directly in the browser without having to edit your source page — kind of like a command-line for JavaScript. Get it now. The Ninja waits.

Let's Get Started

Before diving deep into the library, let's first limber up with some stretching. Exploring the natural language syntax is a good place to start.

// Get today's date
Date.today();

// Add 5 days to today
Date.today().add(5).days();

// Get Friday of this week
Date.friday();

// Get March of this year
Date.march();

// Is today Friday?
Date.today().is().friday();  // true|false

// What day is it?
Date.today().getDayName();

Everything ok? A little out of breath? Soooo sorry.

Now, some Date Assassin exercises.

// Get the first Monday of the year
Date.january().first().monday()

// Get the last Friday of the year
Date.dec().final().fri()

// Set a date to the 15th of the current month at 4:30 PM,
// then add 90 days and make sure that date is a weekday,
// else move to the next weekday.
var d1 = Date.today()
    .set({ day: 15, hour: 16, minute: 30 })
    .add({ days: 90 })
if (!d1.isWeekday()) {
    d1.next().monday();
}

How about letting your users enter a few dates? Say into an <input> field or date picker? Included with the Datejs library is a powerful replacement for the native JavaScript Date parser.

The following examples all start with a String value that we convert into a Date object.

// Lets start simple. "Today"
Date.parse('today');

// How about tomorrow?
Date.parse('tomorrow');

// July 8?
Date.parse('July 8');

// With a year?
Date.parse('July 8th, 2007');

// And time?
Date.parse('July 8th, 2007, 10:30 PM');

// Get the date, move to Monday (if not already Monday),
// then alert the date to the user in a different format.
var d1 = Date.parse('8-Jul-2007');
if (!d1.is().monday()) {
    d1.last().monday();
}
alert(d1.toString('dddd, MMMM d, yyyy'));

The library also includes some Number fun. In order to execute functions directly on JavaScript Number objects, the number must be wrapped in parentheses. This is a requirement of JavaScript. If the number is declared first, the parentheses are not required.

// Get a date 3 days from now
(3).days().fromNow();

// 6 month ago
(6).months().ago();

// 12 weeks from now
var n = 12;
n.weeks().fromNow();

// Get a date 30 days after a user supplied date
var d1 = Date.parse('07.15.2007');
var d2 = (30).days().after(d1);

Step #3 - Refine your skillz

You are nearing a state of Date Ninja-ness, but more experience is required.

Please be sure to check out the following list of resources for further training.

The Datejs Library also includes good size Test Suite, which is worth browsing to get a idea of what's possible.

Hope this helps.

75 Comments

  1. Some functions are not working properly

    // Get a date 30 days after a user supplied date
    var d1 = Date.parse(‘07.15.2007’);
    var d2 = (30).days().after(d1);

    the function after give js error
    Please check and let me inform

    Regards
    Amit srivastava

    Comment by Amit Srivastava — March 17, 2010 @ 10:27 pm

  2. Seems to have trouble converting “12:00 PM”:
    2010-06-23 12:00 AM – parses correctly
    2010-06-23 12:00 PM – parses as 12 AM
    2010-06-23 01:00 AM – parses correctly
    2010-06-23 01:00 PM – parses correctly

    Comment by Heath — June 23, 2010 @ 8:47 am

  3. Disregard that, I’m silly.

    Comment by Heath — June 23, 2010 @ 8:54 am

  4. Quick and clean jQuery DatePicker integration:

    Modify DatePicker’s parseDate function. After initial validation:

    if (value == ”) return null;

    Comment out the rest of the function. Replace with:

    var dateJsParseAttemptDate = Date.parse(value);
    if(dateJsParseAttemptDate) return dateJsParseAttemptDate;
    throw ‘Invalid date’;

    Comment by Igor — July 6, 2010 @ 3:55 pm

  5. Damm. If only I’d come across this two weeks ago. I s’pose I can play with dates in JS the same way I do in Rails now 🙂

    Thanks

    Comment by Danny Smith — July 20, 2010 @ 2:24 pm

  6. Will someone please tell me why we can’t get Date.parse to correctly parse 12:00 AM or 12:00 PM????

    It is not recognizing 12:00 PM as a valid value. And 12:00 AM is parsed as 12:00 PM.

    We’ve stripped out everything but jquery 1.4.3 and datejs.

    It’s pretty damn basic, so I’m not sure what else we should try.

    Thanks!

    Comment by patrick — November 18, 2010 @ 7:44 am

  7. nevermind… you really need to update the links to the current code version 🙂

    Comment by patrick — November 18, 2010 @ 8:01 am

  8. I changed the the getDayName function to accept 1,2 or 3 as the abbreviating parameter as I couldn’t find anyway to getDayInitial.

    Date.prototype.getDayName=function(abbrev){
    return abbrev==3?
    Date.CultureInfo.abbreviatedDayNames[this.getDay()]:
    abbrev==2?
    Date.CultureInfo.shortestDayNames[this.getDay()]:
    abbrev==1?
    Date.CultureInfo.firstLetterDayNames[this.getDay()]:
    Date.CultureInfo.dayNames[this.getDay()];};

    Comment by Scilly_guy — December 27, 2010 @ 7:25 am

  9. […] This is absolutely a library I recommend using if you need to work with date and time in JavaScript. Be sure to check out their getting started guide. […]

    Pingback by Date and time handling in JavaScript using DateJs | Alexander Nyquist — March 19, 2011 @ 6:10 am

  10. How to print timezone?

    hh:mm:ss ??

    Comment by Aakaash — May 13, 2011 @ 12:04 am

  11. […] 2 imports the Datejs library. You will have to download it and install via these instructions. Lines 5-23 calculates each of the date elements that I will need to piece together the final […]

    Pingback by JavaScript Date Ranges/Calculations with Datejs — July 30, 2011 @ 1:18 am

  12. Hi,
    Great script. Only I think I found a potentially potent bug!
    I am using the mi-NZ version and using Date.parse(“dd/mm/yyyy hh:mm tt”) format i.e. 30/09/2011 11:07 pm however 12:07 am gives me a date with getHours() = 12 and 12:07pm gives me a date with getHours() = 12. Everything else is working fine ie. 1am returns 1, 2am returns 2, 2pm returns 14 etc. 12am should return 0?

    How would I go about correcting this?

    Cheers,
    Le-roy

    Comment by Le-roy — September 29, 2011 @ 4:59 pm

  13. very good library, saved me much time! THX!

    Comment by ringo — October 10, 2011 @ 6:22 am

  14. Good script but don’t seems to work with Jquery UI Date picker… :/

    Comment by Romain — November 28, 2011 @ 6:34 am

  15. I think this page is deprecated you should use the google-code page instead (http://code.google.com/p/datejs/).

    don’t forget to include “sugarpak.js” to use all the syntactical sugar used in the examples like “after()”.

    Comment by binary — January 31, 2012 @ 7:31 am

  16. Note http://code.google.com/p/datejs/downloads/list has not been updated since 2007.

    SEE INSTEAD https://github.com/timrwood/moment

    Comment by Martin Cleaver — February 16, 2012 @ 3:29 am

  17. I am having a conflict when using DateJS on the same page as ExtJS. Does DateJS support its own namespace so it can be referenced without naming conflicts with other libraries?

    Comment by Steve — March 4, 2012 @ 6:02 pm

  18. Hello,
    This is excellent work and saved a tones of time for me,
    Thank you !

    Comment by Harpreet — March 30, 2012 @ 7:21 am

  19. Fantastic work! I love your method names and how well you made it english-like.

    Comment by Anthony — April 4, 2012 @ 12:17 pm

  20. Would be good, if someone can add a method which returns end of day as well!

    Comment by Discover — April 18, 2012 @ 3:46 am

  21. Hi guys… JsSimpleDateFormat can parse the formatted string back to the Date Object

    http://www.javascriptsource.com/repository/javascripts/2009/03/880961/JsSimpleDateFormat-demo.html

    Two ways functions.. Could the others do this?
    It uses format as Java format

    Comment by John — May 14, 2012 @ 11:10 pm

  22. […] you looked at datejs? (using the appropriate globalization pack to parse dd/mm/yyyy […]

    Pingback by How to check if input date is equal to today's date? | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes — May 21, 2012 @ 3:23 am

  23. Thank you so much, works great for me.
    I’ve used it to parse dates into UNIX datetime format from a standard form.

    @dehsinotsa

    Comment by Dehsinotsa — May 25, 2012 @ 3:57 am

  24. […] Datejs you should parse the values from the input field using Date.parse(startDate). Check out the Getting Started. If you decide not to use DateJs, you could append getTime() to the startTime var. (e.g. – […]

    Pingback by Comparing Time using Javascript | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes — June 2, 2012 @ 12:02 am

  25. Would be real nice if we could parse the xsl standard period (PnYnMnDTnHnMnS) Then I could do things like Date.parse(“P2Y2M1W1D”). Ok, thats a weird example, but I see you already have simple version such as 1Y but when I try the one that I need to do “3W” for today + 3 weeks, I get NaN.

    Comment by Phil — March 31, 2016 @ 7:00 am

Leave a comment