angular $http.post changing date to UTC date

别来无恙 提交于 2021-02-18 08:51:08

问题


I was trying to post some data to my REST api which has date. Now while I debug, my date parameter is a JS Date object with correct date in my timezone: Tue Apr 04 2017 00:00:00 GMT+0530

after it leaves my code, and I see the same in network tab, it is converted to UTC date: "2017-04-03T18:30:00.000Z"

I searched for the solution according to which I need to include locale file of angular in my index.html which I did:

<script type="text/javascript" src="resources/js/angular/angular-locale_en-in.js"></script>

but it doesn't help. I've seen solutions like adding date format to filter or something, but I want a global solution. Any help? Thanks :)


回答1:


Handling date, time, and timezone have confused me too. May be this answer gives you some insight on how you can handle them.

Try the following code in Chrome's developer console and see how same date is presented in different formats:

var date = new Date();
date.toISOString(); // "2017-04-29T09:54:28.714Z"
date.toGMTString(); //"Sat, 29 Apr 2017 09:54:28 GMT"
date.toLocalString(); //"4/29/2017, 3:24:28 PM"

Any date that you create on client always records the date at zero timezone offset i.e. UTC+/-00:00 Z. For simplicity you may think UTC and GMT as same. When it comes to display purpose the same date is presented as per the browser's timezone. If you do console.log (date) it'll output Sat Apr 29 2017 15:24:28 GMT+0530 (IST) but that doesn't mean that the internal recording of the date is as per browser's timezone. It's just presented on screen/console as per browser's timezone.

Look at date representations not as being converted from one timezone to another but look at them as different representation of the same date. In your browser it is represented as GMT+0530 offset and when it is sent to server it is the same date at zero timezone offset.

As per your comment, if you choose 4th Apr at 00:00 AM in GMT+0530 timezone, internally it'll be 3rd Apr at 18:30 PM in at GMT+0 i.e. zero timezone offset. Let it go to server as it is. When you need to use this date, it comes back from server as 3rd Apr and it'll be displayed in browser as per the browser's timezone offset. There is no conversion involved, it is one date with different representation.

I once asked a related question, may be this adds more clarification.

And overall, this answer is still same as @geminiousgoel and @charlietfl answers.




回答2:


Scenario :

Send date from UI into API call as an epoch time (UNIX Time) instead of date string. You can use getTime() method to convert the date into epoch time.

var dateStr = "Tue Apr 04 2017 00:00:00 GMT+0530";

var dateEpoch = new Date(dateStr).getTime();

console.log(dateEpoch); // 1491244200000 (Local Time)

At receiver end, they have to convert this epoch time (UNIX time) into Date again.It will give the same local date\time that pass from the UI.

Sample screenshot




回答3:


Like charlietfl suggested, probably the global hack would be to override Date.prototype.toJSON() method, but that's not a good practice.

Where are you using your $http.post call? The best place to submit an $http request would be in a service. If you use a service, then I suggest you to enwrap your public service API, so that you could have "public" and "private" methods: these could be utilities to perform common operations, such as data transformations, validations..

angular.service('bookStoreService', ['$http'], function($http) {
    var normalizeBooks = function(booksArray){
        booksArray.forEach(function(book){  
            // do something on the book
        });
    };

    var updateBooks = function(books){
       normalizeBooks(books);
       $http.post('myurl', books);
    };

    return {
       updateBooks : updateBooks
    };
});



回答4:


Passing UTC date to server is desired behavior. The client APIs are supposed to handle UTC time instead of assuming the dates are all local dates.

But anyways, you can convert the date to string based on local time zone, and pass the string to server.




回答5:


i think you just can pass it as string (if the api you use accept strings) with the format you need, let say "Tue Apr 04 2017 00:00:00 GMT+0530" and save it in back-end as string and then when you retrieve it, it will be string and so it will not be changed in any way.




回答6:


Jindal saab, It will work like this. When we select any date with date picker or just pass any value it takes the original local date but when we pass that value further it converts it into UTC, thereafter it needs to convert to local zone again at receiving end. Database saves date-time in UTC format.




回答7:


Did you added the angular-locale_en-in.js library to your app? Something like this....

angular.module('myAngularApp', [
    'ngLocale'])

Otherwise, the js library won't have any effect in your angular application.




回答8:


Append UTC at the end so that Browser converts it into UTC date

var dateToServer =new Date(dateFromUser+" UTC"); now the dateToServer will be UTC DateTime format.




回答9:


Json serializer parse date from string. On a client the date properties are stored as local date in browser time zone. When you are posting your object to server all date properties converts to utc string. In most cases it is a properly behavor. But sometimes you need set and send date in a server time zone. Often it is need when you should set only date whitout time. In that case you should define string propertie and set it manualy. I usaly apply this trick.

class Obj{
 d: Date
}

class ObjDto{
 constructor(obj: Obj){
   this.d= dateTimeToIsoLocalDateString(obj.d)
 }
 d: string
}

...

export function DateTimeToDate(date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}

export function dateTimeToIsoLocalDateString(dateTime: Date): string {
    if (dateTime === null) {
        return null;
    }
    let date = DateTimeToDate(dateTime);
    let res = date.toISOString().replace("Z", "");
    return res;
}

For more understanding this theme you may learn this topic




回答10:


//in res data of rest service in x the value is date in y value of y-axis     
     for (const i in res) {
        console.log(i);
        const a = {x: new Date(this.mimikatzlog[i].x), y: this.mimikatzlog[i].y};
        this.policies.push(a);


来源:https://stackoverflow.com/questions/43496920/angular-http-post-changing-date-to-utc-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!