How do you convert a JavaScript date to UTC?

后端 未结 29 2082
无人共我
无人共我 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:11

    Using moment package, you can easily convert a date string of UTC to a new Date object:

    const moment = require('moment');
    let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
    let utc = b.toUTCString();
    b.getTime();
    

    This specially helps when your server do not support timezone and you want to store UTC date always in server and get it back as a new Date object. Above code worked for my requirement of similar issue that this thread is for. Sharing here so that it can help others. I do not see exactly above solution in any answer. Thanks.

    0 讨论(0)
  • 2020-11-22 01:11

    So this is the way I had to do it because i still wanted a JavaScript date object to manipulate as a date and unfortunantly alot of these answers require you to go to a string.

    //First i had a string called stringDateVar that i needed to convert to Date
    var newDate = new Date(stringDateVar)
    
    //output: 2019-01-07T04:00:00.000Z
    //I needed it 2019-01-07T00:00:00.000Z because i had other logic that was dependent on that 
    
    var correctDate = new Date(newDate.setUTCHours(0))
    
    //This will output 2019-01-07T00:00:00.000Z on everything which allows scalability 
    
    0 讨论(0)
  • 2020-11-22 01:12

    Convert to ISO without changing date/time

    var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time) 
    var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
    //OUTPUT : 2015-02-20T19:29:31.238Z
    

    Convert to ISO with change in date/time(date/time will be changed)

    isoDate = new Date(now).toISOString();
    //OUTPUT : 2015-02-20T13:59:31.238Z 
    

    Fiddle link

    0 讨论(0)
  • 2020-11-22 01:15

    I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.

    You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:

    $.parseDate('yy-mm-dd', '2007-01-26');
    
    0 讨论(0)
  • 2020-11-22 01:16

    This is what I have done in the past:

    var utcDateString = new Date(new Date().toUTCString()).toISOString();
    
    0 讨论(0)
  • 2020-11-22 01:17
    var myDate = new Date(); // Set this to your date in whichever timezone.
    var utcDate = myDate.toUTCString();
    
    0 讨论(0)
提交回复
热议问题