Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment format returns invalid date

i have a date which i formated using moment to be shown like this: 03/04/2105. I want to transform it to iso using moment again. As a result i'm writing:

const IsoDateTo = moment(dateTo).format('YYYY-MM-DD[T]HH:mm:ss');

The date to is 23/04/2105 but the IsoDateTo is returning something like this: 2105-03-04T00:00:00 Also when i enter a date greater than 12 it returns me Invalid Date. Why is this happening?

like image 537
user7334203 Avatar asked May 08 '17 12:05

user7334203


People also ask

Why is moment invalid date?

To prevent "Invalid date" with Moment. js and JavaScript, we can check if a date is valid with the isValid method. to create moment objects with a valid and invalid date string. Then we can call inValid on each to check if they're valid dates.

Is Moment date valid?

isValid(); Moment applies stricter initialization rules than the Date constructor. You can check whether the Moment considers the date invalid using moment#isValid . You can check the metrics used by #isValid using moment#parsingFlags , which returns an object.

What does invalid date format mean?

Unclean or Invalid Dates (DMY Format) should be converted to valid data formats. By default, Excel accepts date input in MM/DD/YY format (US format) unless you change the control panel settings of your PC. Example 22.10. 2007 or 22/10/2007 date may be considered invalid.

How do I change a moment date to a specific format?

Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.


2 Answers

To make sure that you are correctly parsing the string you want to pass the expected string format along to the momentjs (something like this):

const IsoDateTo = moment(dateTo,'DD/MM/YYYY').format('YYYY-MM-DD[T]HH:mm:ss');
like image 100
Vladimir M Avatar answered Sep 19 '22 07:09

Vladimir M


You cannot just throw any date format into it and expect it to magically recognize the format. Moment.js relies on the date parsing functionality of JavaScript if you do not specify and other format. According to the MDN specification of Date, "dateString" can be either IETF-compliant RFC 2822 timestamps or a version of ISO8601. Your date string is neither of it.

It is usually the best to use a date format like YYYY-MM-DD.

const IsoDateTo = moment('2105-03-04').format('YYYY-MM-DD[T]HH:mm:ss');
like image 28
str Avatar answered Sep 18 '22 07:09

str