Convert UTC date time to local date time

前端 未结 30 1153
悲哀的现实
悲哀的现实 2020-11-22 01:09

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time. I want to convert it to the current user’s browser time us

30条回答
  •  你的背包
    2020-11-22 01:43

    In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.

    More info here:

    • http://www.w3.org/TR/NOTE-datetime
    • https://en.wikipedia.org/wiki/ISO_8601

    IN this case the server would return '2011-06-29T16:52:48.000Z' which would feed directly into the JS Date object.

    var utcDate = '2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
    var localDate = new Date(utcDate);
    

    The localDate will be in the right local time which in my case would be two hours later (DK time).

    You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.

提交回复
热议问题