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?
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.
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.
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.
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.
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');
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With