guidoman
guidoman

Reputation: 1131

Moment.js parsing text as date doesn't seem to match locale

String 12.01.2015 e.g. in Germany stands for Jan 12 2015. But the following code doesn't work as expected:

moment.locale('de');
moment('12.01.2015').toString(); // "Tue Dec 01 2015 00:00:00 GMT+0100"
moment('12.01.2015').fromNow(); // "in einem Jahr" (==> locale setting is OK)

In locale/de.js there's the following:

longDateFormat : {
    ...
    L : 'DD.MM.YYYY',
    ...
}

Why isn't the string parsed as I think it should?

Upvotes: 3

Views: 1498

Answers (2)

k-nut
k-nut

Reputation: 3575

Momen't locale sets the desired output of moment. Not the input. You will need to supply the input format like this:

moment('12.01.2015', 'DD.MM.YYYY')

See this github page for more explanation specifically on how this behaviour will change in the future.

You can wrap this in a function so that you do not have to carry the format with you:

function germanMoment(date){
    return moment(date, 'DD.MM.YYYY')
}

And then you can simply use germanMoment('12.01.2015').fromNow()which will work as desired.

Upvotes: 3

dusky
dusky

Reputation: 1313

Moments parse method excpects an ISO 8601 string. You have to specify the date format.

moment("12.01.2015", "DD.MM.YYYY")

Upvotes: 2

Related Questions