Working with Dates in JavaScript

Given the quite limited built-in functionality for working with dates in JavaScript, here are some bits and pieces I have found useful.

Comparing two dates by value:
oDateOne - oDateTwo === 0
(http://stackoverflow.com/a/7961381)

Checking if a string converts to a valid date:
given
var d = new Date("foo");
test using
Object.prototype.toString.call(d) === "[object Date]" && !isNaN(d.getTime())
(http://stackoverflow.com/q/1353684)

Formatting dates is easy if you’re using jQuery UI:
$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));
(http://stackoverflow.com/a/7022296)
Alternatively, the date formatting capabilities of Moment.js are very useful.

Advertisements

About Jennifer Phillips Campbell

Software Developer and Medieval Historian
This entry was posted in JavaScript. Bookmark the permalink.

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