简体   繁体   中英

Date post from frontend to web api issue

I have some calendar with hour and minute textbox field for capturing datetime in my angular application.

This gets converted to full date like below:

accidentVM.AccidentNotificationDateFull = new Date(accidentVM.AccidentNotificationDate.getFullYear(), accidentVM.AccidentNotificationDate.getMonth(), accidentVM.AccidentNotificationDate.getDate(),
                                                parseInt(accidentVM.AccidentNotificationHour), parseInt(accidentVM.AccidentNotificationMinute), 0);
var notificationDate = accidentVM.AccidentNotificationDateFull;

Now if I post this notificationDate as input in web api and it's becoming different when it reaches to web api because javascript is appending my local timezone (which is + 5:30) in my case.

To avoid this

I did a adjustment in GMT from client side.This is basically taking note of the gmt offset and subtracting or adding it from the input so that it becomes again correct when it reaches to server.

the function looks like

this.convertDate = function (dateVM) {               
                var dateObj = dateVM;
                if (new Date().getTimezoneOffset() < 0) {
                    dateVM = new Date(dateObj.setTime(dateObj.getTime() - new Date().getTimezoneOffset() * 60 * 1000));
                }
                else {
                    dateVM = new Date(dateObj.setTime(dateObj.getTime() + new Date().getTimezoneOffset() * 60 * 1000));
                }                
};

This solved the problem and I see now the correct date time getting posted,however it still appends a T at the end while reaches in server.

See the inputs here from front end 在此处输入图片说明

and when it reaches in web api it becomes

在此处输入图片说明

and corresponding fiddler request

在此处输入图片说明

If you have noticed it's becoming UTC or it's appending Z at the end.

My questing is that if there is any way I can get rid of Z or more specifically DateTime kind should be unspecified/local?

I have added below local date format settings in WebApiConfig class.This will tell web api json formatters to convert to local timezone.

var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;

thus I don't need the explicit client side maneuvering of GMT.

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