How do you convert a JavaScript date to UTC?

后端 未结 29 2496
无人共我
无人共我 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 01:18

    If you are dealing with dates a lot, it's worth using moment.js (http://momentjs.com). The method to convert to UTC would be:

    moment(yourTime).utc()
    

    You can use format to change your date to any format you want:

    moment(yourTime).utc().format("YYYY-MM-DD")
    

    There is offset options in moment as well but there is an additional complementary library for dealing with timezone (http://momentjs.com/timezone/). The time conversion would be as simple as this:

    moment.tz(yourUTCTime, "America/New_York")
    

提交回复
热议问题