0

i use angularjs and i want parse a string to a date my code looks like this:

var d=moment.utc("2011-10-02T22:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            var year =d.year();
             var month =d.month();
             var day =d.day();
            $log.log("MOMENTS:"+"year: "+year+" month: "+month+" day: "+day);

the date should be "3 october 2011"

but in the log is :MOMENTS:year: 2014 month: 2 day: 6

this date is completly wrong, why is this so and what do i wrong ? i want extract the day, month and year

user2115378
  • 931
  • 3
  • 14
  • 22

2 Answers2

1

Here is a fiddle: http://jsfiddle.net/FGa2J/

moment.day() returns the day of the week (not the day of the month) you need moment.date() for that. moment.month() is 0 based, so you will get 9 for October. Also, it seems like moment can parse your date string just fine without specifying the format.

Code from the fiddle:

report ( "2011-10-02T22:00:00.000Z", ["yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"] );

var d = moment("2011-10-02T22:00:00.000Z");
var year = d.year();
var month = d.month();
var day = d.date();
console.log("MOMENTS:"+"year: "+year+" month: "+(month+1)+" day: "+day);

function report( dateString, formats) {
    $("#results").append (
        $("<li>", { text: 
        dateString + " is valid: " + moment(dateString, formats).isValid()
              })
    );
}
aet
  • 7,192
  • 3
  • 27
  • 25
  • hm it works if i add my string directly to moments.js like in your example.. but why is this not working if i provide the format ? var d=moment.utc("2011-10-02T22:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); or is my format wrong ? – user2115378 May 05 '14 at 10:03
  • I cannot find any documentation for how to add escaping to a parse string. Not sure it even supports that?? Might have to dig into the moment source. – aet May 05 '14 at 16:31
1

You're not using the correct string formatting characters.

You have: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

In moment, it would be: "YYYY-MM-DDTHH:mm:ss.SSSZ"

Note that it's case sensitive, and doesn't necessarily match formats from other languages (.Net, PHP, etc).

However - since this is the ISO-8601 standard format, it is detected and supported automatically. You should simply omit that parameter.

From the documentation:

... Moment.js does detect if you are using an ISO-8601 string and will parse that correctly without a format string.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575