Convert date to UTC using moment.js

后端 未结 11 729
囚心锁ツ
囚心锁ツ 2020-12-13 01:43

Probably and easy answer to this but I can\'t seem to find a way to get moment.js to return a UTC date time in milliseconds. Here is what I am doing:

var dat         


        
相关标签:
11条回答
  • 2020-12-13 01:43

    This worked for me. Others might find it useful.

    // date = 2020-08-31T00:00:00Z I'm located in Denmark (timezone is +2 hours)

    moment.utc(moment(date).utc()).format() // returns 2020-08-30T22:00:00Z

    0 讨论(0)
  • 2020-12-13 01:49

    Don't you need something to compare and then retrieve the milliseconds?

    For instance:

    let enteredDate = $("#txt-date").val(); // get the date entered in the input
    let expires = moment.utc(enteredDate); // convert it into UTC
    

    With that you have the expiring date in UTC. Now you can get the "right-now" date in UTC and compare:

    var rightNowUTC = moment.utc(); // get this moment in UTC based on browser
    let duration = moment.duration(rightNowUTC.diff(expires)); // get the diff
    let remainingTimeInMls = duration.asMilliseconds();
    
    0 讨论(0)
  • 2020-12-13 01:51
    moment.utc(date).format(...); 
    

    is the way to go, since

    moment().utc(date).format(...);
    

    does behave weird...

    0 讨论(0)
  • 2020-12-13 01:55

    This will be the answer:

    moment.utc(moment(localdate)).format()
    
    localdate = '2020-01-01 12:00:00'
    
    moment(localdate)
    //Moment<2020-01-01T12:00:00+08:00>
    
    moment.utc(moment(localdate)).format()
    //2020-01-01T04:00:00Z
    
    0 讨论(0)
  • 2020-12-13 01:57

    This is found in the documentation. With a library like moment, I urge you to read the entirety of the documentation. It's really important.

    Assuming the input text is entered in terms of the users's local time:

     var expires = moment(date).valueOf();
    

    If the user is instructed actually enter a UTC date/time, then:

     var expires = moment.utc(date).valueOf();
    
    0 讨论(0)
  • 2020-12-13 02:02

    As of : moment.js version 2.24.0

    let's say you have a local date input, this is the proper way to convert your dateTime or Time input to UTC :

    var utcStart = new moment("09:00", "HH:mm").utc();
    

    or in case you specify a date

    var utcStart = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc();
    

    As you can see the result output will be returned in UTC :

    //You can call the format() that will return your UTC date in a string 
     utcStart.format(); 
    //Result : 2019-06-24T13:00:00 
    

    But if you do this as below, it will not convert to UTC :

    var myTime = new moment.utc("09:00", "HH:mm"); 
    

    You're only setting your input to utc time, it's as if your mentioning that myTime is in UTC, ....the output will be 9:00

    0 讨论(0)
提交回复
热议问题