Moment.js Convert Local time to UTC time does work

后端 未结 7 1857
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 18:23

I would like to use Moment.js to convert a local time to UTC equivalent. I believe that I have the correct method in place, but it does not alter the time.

I\'m in S

相关标签:
7条回答
  • 2021-01-01 18:48

    I just tried this code and it seems like I get the correct UTC time. I guess I just want to confirm that what I am doing is correct way to access the UTC time from moment.js

    a.format("YYYY-MM-DD HH:mm:ssZ")
    

    "2015-03-18 04:19:46+00:00"

    I found that my usage pattern of in my application was incorrect

    selectedDate.utc().format(fullFormat)
    

    It should have been

    moment.utc(selectedDate).format(fullFormat)
    
    0 讨论(0)
  • 2021-01-01 18:57

    This worked for me !!

    selectedDate = moment(selectedDate).add(moment(selectedDate).utcOffset(), 'm').utc().format()
    
    0 讨论(0)
  • 2021-01-01 19:00

    This works

    moment(date_to_convert).utc().format("YYYY-MM-DD HH:mm:ss");
    
    0 讨论(0)
  • 2021-01-01 19:00

    Create a local moment object from you local time and convert it to UTC then format it, then create a new UTC moment from that formatted UTC string

    var localDateString = '24/04/2019';
    var localDateStringFormat = 'DD/MM/YYYY';
    
    var utcMoment = moment.utc(moment(localDateString, localDateStringFormat ).utc().format('YYYY-MM-DD HH:mm:ssZ'))
    
    console.log(utcMoment);
    <script src="https://momentjs.com/downloads/moment.js"></script>

    0 讨论(0)
  • 2021-01-01 19:01

    This is how you do it using moment-timezone

    moment.tz(localDate, localTimeZone).utc()
    
    0 讨论(0)
  • 2021-01-01 19:05

    The question is old, but I also faced it. It may be useful to someone:

    Using the method of utcOffset() to calculate the UTC time:

    selectedDate = (moment(selectedDate).add(-(moment().utcOffset()), 'm'));
    

    And explicitly specify UTC:

    selectedDate = moment.parseZone(selectedDate).utc().format();
    
    0 讨论(0)
提交回复
热议问题