New .same() Function, But Is It Useful?

May 13th, 2008 | Code

I need some feedback regarding a feature I just added to the library, but I'm struggling to explain/document clearly and I'm not sure if others would find this useful.

The new .same() function will compare two date objects to determine if they occur on/in exactly the same instance of the given date part. (...like I said, I'm having a hard time explaining this one).

It's easier to understand with code...

Scenario: Determine if the two dates occur on the same day.

Example

var d1 = Date.today(); // today at 00:00
var d2 = new Date();   // exactly now.

// Do they occur on the same day?
d1.same().day(d2); // true

// What if it's the same day, but one year apart?
var nextYear = Date.today().add(1).year();

d1.same().day(nextYear); // false, because the dates must occur on the exact same day.

When comparing the dates in the same above, the .same() function will test that the year, month, and day match. Because we're only interested in whether the day is the same, the hour, minute, second & millisecond values are ignored.

Using the same d1 & d2 values from above, determine if the two dates occur on the same hour.

Example

// Do they occur on the same hour?
d1.same().hour(d2); // false, unless d2 hour is '00' (< 1:00 am).

If no date is passed as a parameter, by default the .same() function will use 'Now' (new Date()) as the default date to compare against.

Example

Date.today().same().day(); // true, 'today' occurs on 'today'
Date.today().same().hour(); // false, unless 'now' is '00' minutes (< 1:00am)

What do think? Would you find this functionality useful?

I do... because I'm often trying to determine if some date object occurs during today. The following samples demonstrate various ways to determine if a date object occurs today.

Example (native JavaScript, without Datejs)

var temp = new Date();
temp.setHours(0);
temp.setMinutes(0);
temp.setSeconds(0);
temp.setMilliseconds(0);

var today = new Date(someDate.getTime()); // clone original instance so we don't actually change the original date.
var today.setHours(0);
var today.setMinutes(0);
var today.setSeconds(0);
var today.setMilliseconds(0);

(today == temp); // true|false

Example (with Datejs)

// with Datejs, but without .same
someDate.clone().clearTime().equals(Date.today());

// New
someDate.same().day();

// Or,
someDate.is().today();

Checking if a given date object occurs today is easy enough with Datejs and would not really justify adding the new .same() functionality, but things can get nasty when you need to compare against a date other than 'today'.

Scenario: Determine if a given date occurs during some week period 2 months from now.

Example

// New
var future = Date.today().add(2).months();

return someDate.same().week(future); // true|false;

The .same() function adds a third context to .second() within the library, which enables the following interesting (but freakishly cryptic) logic.

Example

Date.jan().second().monday().add(1).second().same().second();

The .same() functionality has been added to sugarpak.js and is available from SVN.

Any feedback is appreciated.

Refreshed Documentation

April 13th, 2008 | News

For the last couple months updates to the library have been consistently happening every 3-4 days with new features, bug fixes or edits being committed to SVN. The last few days in particular have seen an epic refresh to the project with updates across all modules.

View CHANGELOG

With all the recent changes the docs have gotten a little out of sync, so today I finally sat down to make sure all the core.js docs were correct both online (wiki) and inline. Along with sync I also created a new documentation style for the online wiki docs.

New Documentation Sample
New Datejs Documentation Style

Each function is now documented with the following features:

  • A description of the function
  • Parameters are listed with Type, Name and Description
  • Return Value is listed with the Type, Sample and Description
  • At least one code sample demonstrating how to use the function

Documenting sugarpak.js is up next.

Hope this helps.

Tags:

Need Feedback From Arabic, Chinese And Several Other Cultures

February 10th, 2008 | Code

In preparation for an official final Release Version 1.0 within a month or two, we're just about to stamp the current Datejs code in SVN as Beta.

But... we need some help. One area where we have not received much feedback is testing the Parser with cultures/languages outside of English.

The Datejs library should properly parse month and day names (both full and abbreviated strings) in over 150 different cultures.

The variations of German, Spanish, French and most European culture parsing seem good.

The big unknown cultures are Arabic and Chinese.

Haven't heard much feedback from India either.

The following list details the cultures we're most interested in receiving feedback:

If any developers could confirm the Datejs Parser is working (or not) in any of the above cultures, we would really appreciate the thumbs up/down. By "working", we're specifically interested in whether the Parser is correctly parsing Day and Month names in each culture and whether the expected date format for that culture parses properly.

If the following strings (translated into the appropriate language) return the proper date, things should be good.

Example

Date.parse('July 2008');
Date.parse('Sat July 3, 2004');
Date.parse('Dec');
Date.parse('monday');

The parser ships with some date phrase support (eg. 'today', 'next march'), although those strings may require translation. A couple cultures have already been translated by the community and available for download from the Datejs forums.

To test your culture, download a culture-specific file from SVN /trunk/build/ and add to any web page. If you are using FireFox, the easiest way run test scripts is with FireBug.

Thanks for the help.

Advice On Datejs Compression And Performance Tuning

January 22nd, 2008 | Code

Guy Fraser recently chronicled a series of his recommendations for Datejs compression and performance enhancements. Check it out.

One recommendation from Guy was to hold a reference to the Date.prototype in a local var, thereby saving characters and simplifying access to the prototype.

Example

(function () {
    // Store prototype in local variable making
    // syntax shorter and access faster.
    var $P = Date.prototype;

    // Old
    // Date.prototype.clearTime = function() {

    // New
    $P.clearTime = function () {
        this.setHours(0);
        this.setMinutes(0);
        this.setSeconds(0);
        this.setMilliseconds(0);
        return this;
    };
}());

After changing everything over we were able to shave a little over 1k off the total library size and our performance tests did register an improvement. Great advice, and Datejs is now better (and faster!).

All this has been checked into SVN for public consumption.

Ajaxorized Sliding Date-Picker

January 22nd, 2008 | News

SliderWillem from Ajaxorized has just glued together Prototype, Scriptaculous and Datejs to create a super cool sliding date-picker widget.

Check it out.

CrazyEgg Confetti Report

December 11th, 2007 | News

Over the weekend we ran a test with CrazyEgg to get a sense of what visitors were clicking on. We were pretty sure the "Mad Skillz" widget was a popular first stop for most, but wow!

The CrazyEgg Confetti report confirmed our hunch.

CrazyEgg Confetti detail
[See full report]

I have a few ideas on how to improve the "Mad Skillz" widget and maybe we'll make it an even bigger focus on the home page. I'd also like to figure out a way to start capturing any parse failures. A simple button which would do a one-click submit and email us the contents of the input field should be easy to implement.

SVN Commits And New Sugar

December 10th, 2007 | Code

Since the Alpha 1 launch a couple weeks ago we've been steadily hammering away at Datejs enhancements, writing tests and pushing towards our goal of a solid Beta 1 release for early January 2008.

The launch went well and community feedback has been steady and very much appreciated. As defects are discovered we're doing our best to fix immediately and commit the new code to SVN.

Datejs SVN Commit messagesIf you're interested in following along as we commit code to the source repository, you might want to subscribe to the Datejs-commits Discussion Group. The Datejs-commits Group automagically catches all the SVN commit log messages and creates a feed which is then easily consumed into your favourite news reader. We're doing our best to always ensure the SVN log notes give plenty of detail regarding all new code and/or revisions.

A spoonful of SugarPak

For developers partial to the RememberTheMilk.com date input options we added the following API functions and abbreviations.

Date.tod();       // Date.today()
Date.tomorrow();
Date.tom();
Date.yesterday();
Date.yes();

Added a new .at() function which accepts a Time string or Time config object.

Date.today().at("6:15 PM");
Date.today().at({hour: 18, minute: 15});

Added .next() and .last() as static functions to the Date object, so you no longer need to instantiate a Date object first before calling .next() or .last().

// Existing
Date.today().next().friday();
Date.today().last().march();

// New
// The above code still works,
// but if you want to be relative to 'today',
// the following code is tighter.
Date.next().friday();
Date.last().march();

Date logic actually gets fun to write when you start combining the functions to build amazingly readable Date expressions.

Date.next().friday().at("6:15 PM");

[Use Case] Schedule a reminder to be sent a week before the start of the next month at 9 in the morning.

(1).week().before(Date.next().month()).at("9:00 am");

Hope this helps.

Ajaxian + 24 Hours

December 4th, 2007 | News

Well, it certainly was an interesting finish to November.

Late afternoon on Date.parse("Tuesday, November 28, 2007") Ajaxian published a blog post about the Datejs library and within the subsequent 24 hours, 30,000 deadly Datejs ninjas began their training.

30000 Datejs Downloads

I thought people might be interested in seeing some of the community feedback and hard traffic stats we received during that first 24 hours.

AjaxianLet's kick it off where it all started — the "Mad Cool Date Library" Ajaxian blog post by Rey Bango.

"Holy cow!!! All I have to say is wow. This is a VERY cool date library and definitely unique. I’ve not seen anything like this."

When I first saw the post title I read it as "Mad Cow Date Library" and thought, ooh... that sounds interesting. Totally did not make the connection to Datejs at first. Yes, I'm a hoser.

The comments section lit up instantly with opinions and feedback.

 

MashableAround that same time the post "Datejs: A Truly Slick Date Script" by Mark 'Rizzn' Hopkins at Mashable came online.

"It isn’t often when I come across a JavaScript so cool that I feel I must blog about it. In fact, I don’t think I’ve ever come across such a JavaScript before today. Datejs earns this elusive distinction today because it's just so darn good at what it does."

"It is everything I've ever wanted in a form date validation tool, but didn't have the patience to program. Datejs is fast, too. I’m stuck using one of my slowest machines today, and there is no noticeable delay between the typing and the translation of the date."

 

WiredA similar post by Scott Gilbertson at Wired Monkeybites "Sleek JavaScript Library Solves Your Dating Woes".

"It's not often that we run across a JavaScript library that's cool enough to warrant a post, but Datejs really is that cool."

 

Dan Yoder (who is also the co-author of Datejs) posted an excellent introduction to the library and a few thoughts on where we're heading. Check it out.

"...JavaScript was in dire need of a comprehensive and straightforward Date library. And now it has one."

A few others from the Blogosphere...
Marc Grabanski
WebAppers
AJAX Magazine
Black Belt Coder
Dylan Schiemann
nForm
The Home of Jon

The community has been incredibly helpful pointing out parsing failures — many of which were edge case bugs we had not been testing for.

Most were fixed within a few hours.

There's obviously still a lot of work to do with date expressions, but I think we're off to a good start and broader support will come over time. To get the full scope of what the Parser will parse, please browse through the Datejs Test Suite.

Stats from Google Analytics

Total Hits

Visitor Overview

We watched the hit and download count increase pretty steadily throughout the day, but quickly noticed a growing disconnect between the number of hits on the datejs.com website and the total downloads. At the end of the first 24 hours, total website traffic had just passed 6,500 hits, with about 1/2 of that coming directly from Ajaxian. We were expecting a lot more traffic to register from Ajaxian, especially given the 30,000 downloads.

So, the question was, where were all the downloads coming from?

It took some head scratching, but eventually we went back to the Ajaxian post and noticed the very last link, linked directly to the GoogleCode download page. See

Ajaxian - link to download

Unfortunately Analytics does not record stats from the GoogleCode file download pages. That kinda sucks, although the total download count does give us a pretty good idea that the vast majority of Ajaxian readers (I guess approx 20,000) must have clicked the very last link in the post and were shot off directly to the GoogleCode download page, bypassing the datejs.com website. That's pretty interesting and unfortunate because most would have missed the "Mad Skillz" widget on the home page. Oh well.

Visitors by Browser

Huge FireFox usage. Not surprising I guess, given the crowd.

Visitors by Browser

Visitors by Operating System

Check out the 9 iPhone and 2 iPod hits!

Visitors by Operating System

Visitors by Country

Visitors by Country

 

After all was said and done I think it went well and the library is better because of the feedback. Keep it coming.

Please feel free to contact us or post to the forums if you have any questions or comments and we'll do our best to help out.

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.

Datejs is here

November 19th, 2007 | News

Datejs PreviewWe’re very pleased to announce that Datejs has arrived. KaBoom!

So, what is Datejs?

Datejs is an open-source JavaScript Date library.

For a long time, dates have been ignored in the world of JavaScript. Datejs is now the ultimate JavaScript warrior for not only parsing, but formatting and processing as well.

Datejs is comprehensive, yet simple, stealthy and fast.

Date objects need no longer be feared, for when they least expect it, Datejs shall silently leap from the shadows of the web and drive a katana of logic deep into the their heats, rendering them instantly and thoroughly, parsed.

Download the library to get started.