Dealing With Dates in JavaScript

Sharing is Caring

Dates and DateTimes are difficult to deal with in most languages. The Date object is a datatype that’s built in the JavaScript language. In JavaScript, the biggest problem is that the browsers aren’t overly consistent in the way they have implemented the Date object and its APIs.

A new Date object can be created like this:

var dt = new Date();

After we’ve created a Date, we’re able to do quite a few different operations on it like set the year, month, year, or convert to local time or UTC time.

The default constructor creates a date object set to the current local date and time. The constructor is overloaded, so it can accept other parameters like the numer of milliseconds since the Unix Epoch (01/01/1970) or a date string.

For example:

var dtFromMilliseconds = new Date(1493776425266);
console.log(dtFromMilliseconds)

Would display “Tue May 02 2017 21:53:45 GMT-0400 (Eastern Daylight Time)” if you were in Eastern Daylight time. The biggest problem with Dates and JavaScript is that the implementation of the format isn’t always consistent so it’s very difficult to send this to an API in a consistent and proper format. There’s quite a few different libraries that are available for manipulating dates.

In a past project, I had a need to add dates, determine if it was a leap year and determine number of hours between different times, which would have required quite a bit of utility code and logic. At the time, I decided to use Datejs which worked pretty well. It so adds a lot of awesome methods and other functionality that allows developers to stop worrying so much about dates and just get the project working.

Over the last year, I’ve been working a lot with AWS Lambda and started using momentjs which feels a lot more intuitive and seems to work with a lot more of the crazy formats that dates and datetimes can be found in.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.