简体   繁体   中英

Changing date format from dd/mm/yyyy to yyyy-mm-dd in knockout.js

I have no experience of using knockout.js. I've inherited a booking form which uses a mixture of knockout and C# ASP.NET. We recently upgraded the database to the latest version of MySQL, which is a lot more particular about the format in which the date is entered than the older version. In most cases I've been able to get around this by tweaking either C# or SQL, but in one part of the form I haven't found a solution. The dates are prepopulated in the form input in dd/mm/yyyy format. I want to change this to yyyy-mm-dd so that I can use date inputs rather than text inputs

There are two form inputs which look like this

<input type="text" size="10" maxlength="10" class="normaltext" data-bind="attr:{id:'returnDate-'+Id},value:FlightInfo.ReturnDate, enable:$root.FlightsAdvanced() == 'true' && !FlightInfo.OwnFlight()">

The other one, obviously, is for the departure date. They appear to be populated from the following function in a javascript file.

function FlightInfo(depDate, retDate) {

 this.OwnFlight = ko.observable(false);
 this.FirstCode = ko.observable("");
 this.SecondCode = ko.observable("");
 this.DepartureDate = ko.observable(depDate);
 this.ReturnDate = ko.observable(retDate);
 this.ReqTransferIn = ko.observable(0);
 this.ReqTransferOut = ko.observable(0);
}

If I replace ko.observable(retDate) with a hard coded date, eg 2020-09-09, and submit the form then it works, however if I hard code the same date directly into the text input in place of value:FlightInfo.ReturnDate then it doesn't - the form takes the date in the wrong format from knockout and an error is thrown.

I've tried using moment.js as suggested in this question , but it didn't work for me. How can I reformat depDate and retDate as yyyy-mm-dd

I eventually solved this in the C# layer by changing a few instances of .ToShortDateString() to .ToShortDateString() .

Using moment.js is the right way to achieve this, when creating flightInfo, two observables should be modified like this:

 this.DepartureDate = ko.observable(moment(depDate).format('YYYY-MM-DD'));
 this.ReturnDate = ko.observable(moment(retDate).format('YYYY-MM-DD'));

if these changes do not reflect in your text input, than you should debug if you have moment.js included and activated in proper manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM