Reputation: 639
I have that date:
02.05.2020 12:33:08
What means:
day 02
month 05
year 2020
hour 12
minute 33
second 08
I want to parse it to a date object via following call, but the returned day is wrong:
moment("02.05.2020 12:33:08").day() => returned 3 ???
Why is it wrong parsed by momentjs?
Upvotes: 1
Views: 1459
Reputation: 30675
I believe you'll need to supply a format to allow moment to parse the date correctly.
See the docs here: Moment parse string+format.
Once you do this, you should get the correct result:
const dateFormat = "DD.MM.YYYY HH:mm:ss";
const parsedDate = moment("02.05.2020 12:33:08", dateFormat);
console.log("Day of week:", parsedDate.day());
console.log("Day of month:", parsedDate.date());
console.log("Full date:", parsedDate.format("dddd, MMMM Do YYYY, HH:mm:ss"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Upvotes: 2
Reputation: 1981
There are two potential problems.
First, if you run just the parsing on its own (like at the command-line REPL, you get the following warning.
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.
So, that might not be the best string to parse, depending on your version.
But also, .day()
gives you a day of the week index. February 5th was a Wednesday, and since Moment is counting days from Sunday, that's almost certainly the right answer. If you want the day of the month (5), that's .date()
, instead.
Actually, there's a third potential problem, in that "02" and "05" make for an ambiguous date, so you probably want to feed Moment a parse string, a second parameter that looks something like "MM.DD.YYYY hh:mm:ss"
.
Upvotes: 1