How do you convert a JavaScript date to UTC?

后端 未结 29 2044
无人共我
无人共我 2020-11-22 00:50

Suppose a user of your website enters a date range.

2009-1-1 to 2009-1-3

You need to send this date to a server for some processing, but th

29条回答
  •  再見小時候
    2020-11-22 00:57

    Another solution to convert to UTC and keep it as a date object: (It works by removing the ' GMT' part from the end of the formatted string, then putting it back into the Date constructor)

    var now = new Date();
    var now_utc = new Date(now.toUTCString().slice(0, -4));
    console.log(now_utc)

    I needed to do this to interface with a datetime picker library. But in general it's a bad idea to work with dates this way.

    Users generally want to work with datetimes in their local time, so you either update the server side code to parse datetime strings with offsets correctly, then convert to UTC (best option) or you convert to a UTC string client-side before sending to the server (like in Will Stern's answer)

提交回复
热议问题