Format DateTime in JavaScript (using jQuery !!)

During some recent project work using jQuery and REST, I was needing to format the current date/time – and use as a filter for a REST query.

eg. From a given site/library, get the most recent 5 items – but only for the last week

http://server/_vti_bin/ListData.svc/library?$select=Id,Path,Name,Title,Modified&$top=5&$orderby=Modified desc&$filter=(Modified ge datetime’2012-10-31T00:00:00′)

It follows that I need to do a “math” function to subtract 7 days from the current date – and THEN – format into the date for the REST query string param.

The first bit was easy :

  • var d = new Date();
  • d.setDate(d.getDate() – 7);

This would mean I now have a date object with “one week ago”.

But – then – how to FORMAT it ??   

Working with the DATE object in JavaScript is a little clunky – to say the least !

From what I could find – the best way was to do this :

  • var curr_date = d.getDate();
  • var curr_month = d.getMonth();
  • curr_month++;   // need to add 1 – as it’s zero based !
  • var curr_year = d.getFullYear();
  • var formattedDate = curr_date + "-" + curr_month + "-" + curr_year);

See more about this approach :

http://www.elated.com/articles/working-with-dates/

This is an overly complex approach – and what happens if my month needs to be zero prefix ?

Eg.   14/09/2012 – instead of 14/9/2012 – or maybe 1/12/2012, or 01/12/2012.

WTF !!?     Sad smile

jQuery to Save The Day !

As I’m working with some jQuery components, and the jQuery UI is also referenced along the way, I can make sure of the “DatePicker” component – to do date-formatting – EASY !!

So – my revised code is :

  • var d = new Date();
  • d.setDate(d.getDate() – 7);
  • var formattedDateTime = $.datepicker.formatDate(‘yy-mm-ddT00:00:00’, d);

 

You could even have a DATEFORMAT for the current date in ONE line – this is soooo much simpler – and much more powerful – and almost akin to a C#/VB.NET formatting approach.

  • var formattedDateTime = $.datepicker.formatDate(‘yy-mm-dd’, new Date());

 

Here’s a few jQuery’ised DateTime Format functions – AWESOME !

$.datepicker.formatDate([FORMAT], new Date());

dd/mm/yy 01/09/2012
d/m/y 1/9/12
d-M-y 1-Sep-12
d-MM-yy 1-September-2012

 

Have a look at the jQuery doco for some more examples – and how-to.

Unfortunately, it doesn’t extend to TIME formatting – doh…!

Hopefully that helps someone out there – and avoids the clunky old-school JavaScript approach. 

It certainly saved ME !    

Viva la jQuery !

Smile with tongue out

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s