Question

I have a string which is allways in this format: 7 May 2012 or 17 May 2012 My goal is to parse this string and get the date in this format: yyyy-mm-dd

So, my example 7 May 2012 will become 2012-05-07 and 17 May 2012 will become 2012-05-17

I have tryed with

Date.parse("7 May 2012", "yyyy-mm-dd") 

but the result is:

Sun May 20 2012 00:00:00 GMT+0200 (CEST)

Thank you very much for your help.

Was it helpful?

Solution

I don't know where you got that Date.parse call, JavaScript's Date.parse has no second argument.

To do this, you'll need to parse the string yourself, or use MomentJS or similar to do it for you. If you want to parse it yourself, you'll probably want a regular expression and a lookup table (for the month names). The regex would be along these lines:

var parts = /^\s*(\d+)\s+([A-Za-z]+)\s+(\d+)\s*$/.exec(str);

...where you'd end up with parts[0] being the day, parts[1] the month name, and parts[2] the year. Then just convert the month to lower or upper case, and use a lookup table to map month name to month number, something along these lines:

var months = {
    "jan": 0,
    "january": 0,
    "feb": 1,
    "february": 1,
    "may": 4,
    // ...
    "dec": 11,
    "december": 11
};
var parts = /^\s*(\d+)\s+([A-Za-z]+)\s+(\d+)\s*$/.exec(str);
var dt;
if (parts) {
    parts[2] = months[parts[2].toLowerCase()];
    if (typeof parts[2] !== "undefined") {
        dt = new Date(parseInt(parts[3], 10),
                      parts[2],
                      parseInt(parts[1], 10));
    }
}

Live example | source

Then you can format the resulting Date object. (Again, there are libs to help there.)

Or, of course, never actually make a Date and just format directly from parts.

OTHER TIPS

That's not how Date.parse works, it just takes one parameter, and it returns a unix timestamp.

If you want a Date object, use new Date.

var myDate = new Date("7 May 2012");
// Mon May 07 2012 00:00:00

You can then parse it yourself into the format you want:

var year = myDate.getFullYear(),
    month = myDate.getMonth() + 1, // month returns 0-11, not 1-12
    day = myDate.getDate();
var dateStr = year + '-' + (month < 10 ? 0 : '') + month + '-' + (day < 10 ? 0 : '') + day;

NOTE: "7 May 2012" is a non-standard date format, and may not work correctly in all browsers.

NOTE 2: To be 100% sure that it'll work in all browsers, I'd use a library like Datejs.

// Using Date.js
var myDate = Date.parse('7 May 2012');
var dateStr = myDate.toString('yyyy-MM-dd');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top