Reputation: 417
I am trying to bind my Ionic DateTime component through ngModel. I get a value from backend which looks like this
"30-07-2021 12:00:00 AM"
Then I process it into -
var date = "30-07-2021 12:00:00 AM"
var finalDate = date.split(" ")[0].split("-");
var fdate =
finalDate[2] +
"-" +
finalDate[1] +
"-" +
finalDate[0];
var ISOdate = new Date(fdate).toISOString()
console.log(ISOdate);
and I get an error "Error parsing date: "2021-07-30T00:00:00.000Z". Please provide a valid ISO 8601 datetime format"
What am I doing wrong here?
Here is my datetime component-
<ion-datetime
(ionChange)="onChange(filters.DTO_Property_Name,$event,filters.Data_Type_Enum)"
cancelText="Clear"
(ionCancel)="clear(filters.Filter_Name)"
[(ngModel)]="myDateValues[filters.Filter_Name]"
displayFormat="DD/MM/YYYY"
>
</ion-datetime>
Upvotes: 0
Views: 1764
Reputation: 147343
More comment than answer.
You're parsing a string like "30-07-2021 12:00:00 AM" by firstly parsing and reformatting it as "2021-07-30 12:00:00 AM" then using the built–in parser. That's not a good idea as the string isn't in a format supported by ECMA-262 so parsing is implementation dependent.
The string should be treated as local, so:
new Date(fdate).toISOString();
should not produce a timestamp like "2021-07-30T00:00:00.000Z" unless your offset is +0 or it's being parsed as UTC (it might also return "Invalid Date" or throw a range error). I'll guess that you want it treated as UTC.
Possibly the ionic parser is getting upset about the decimal seconds produced by toISOString, so either remove them or don't use toISOString.
E.g. just reformat the string, avoiding Date and toISOString:
// Reformat "30-07-2021 12:00:00 AM" to "2021-07-30T00:00:00Z"
function formatTimestamp(ts) {
let [D,M,Y,h,m,s,ap] = ts.toLowerCase().split(/\W/);
h = String(h%12 + (ap == 'am'? 0 : 12)).padStart(2, '0');
return `${Y}-${M}-${D}T${h}:${m}:${s}Z`;
}
console.log(formatTimestamp("30-07-2021 12:00:00 AM"));
Upvotes: 1