Javascript – Create a date object from a date string

Previously, we talked about how to convert a date object into string.
Javascript – Get YYYY-MM-DD string from a Date object

This time, we will do the opposite which parses a date string and create a date object.

// Assume we have the date string in YYYY-MM-DD formate
var datestring = '2013-05-03';

var date_obj = new Date();
date_obj.setYear(parseInt(datestring.substr(0, 4), 10));
date_obj.setMonth(parseInt(datestring.substr(5, 2), 10) - 1);
date_obj.setDate(parseInt(datestring.substr(8, 2), 10));

// Verify the date object


Done =)

Reference: StackOverflow – javascript: how to parse a date string


Leave a Reply

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

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.