Convert (YYYY/MM/DD HH:MM:SS.MS) GMT to local time using JavaScript

别说谁变了你拦得住时间么 提交于 2021-01-29 02:57:16

问题


For some reason, the SOAP response from one of my WebService looks like this:

2010/07/08 04:21:24.477

Where the date format is YYYY/MM/DD and the time is GMT.

I'm not really sure how to convert this to local time because the format is so odd.


回答1:


Date.parse should actually parse most of the date string into its respective timestamp.

The 2 caveats appear to be:

  • Milliseconds aren't supported, so they have to be separated and added after parsing.
  • It'll assume local time, so 'GMT' or 'UTC' should to be appended before parsing.

With these in mind, the following should work:

function parseSoapDate(dateString) {
  var dateParts = dateString.split('.'),
      dateParse = dateParts[0],
      dateMilli = dateParts[1];

  return new Date(
    Date.parse(dateParse + ' GMT') +
    parseInt(dateMilli, 10)
  );
}

var date = parseSoapDate('2010/07/08 04:21:24.477');

As for UTC to local time, JavaScript's Date objects should already handle that for you as they can report the date in both UTC and the user's local timezone. You specify which you want by the name of the method (whether it has UTC in it or not):

alert(date.toString());     // local time
alert(date.toUTCString());  // UTC time



回答2:


This should work:

var dateStr = "2010/07/08 04:21:24.477";
var d = new Date(dateStr.split('.')[0]);
d.setUTCHours(0);



回答3:


my JSON returns: YYYY-MM-DD HH:MM:SS, localization will work only on selected browsers Date.prototype.toLocaleDataString("en-us"[,option] )

    function stringToDate(s) {
        var language = window.navigator.userLanguage || window.navigator.language;
        var options = {year: "numeric", month: "numeric", day: "numeric"};          
        s = s.split(/[-: ]/);           
        d = new Date(Date.UTC(s[0], s[1]-1, s[2], s[3], s[4], s[5]));
        return d.toLocaleDateString( language , options)+" "+d.toLocaleTimeString();
    } 
// return
// Friday, November 15, 2013 2:21:04 PM  --> FF25
// 11/15/2013 2:21:04 PM                 --> Chrome31



回答4:


It looks like the response of the date/time is in ISO format, which is a sensible way to provide date information.

Suppose that the date returned is 7-8-2010. Would this be the 8th of July or the 7th of August? Having the date in ISO format (YYYY/MM/DD) solves this ambiguity.

You can convert this date to the required format in many different ways, i.e.

var input = '2010/07/08 04:21:24.477';
var now = new Date(input.slice(0, input.indexOf('.')));
alert(now.toLocaleString());

You may want to search the Internet for the Date object or to find snippets which will allow you to convert a date using many different formats.



来源:https://stackoverflow.com/questions/3213222/convert-yyyy-mm-dd-hhmmss-ms-gmt-to-local-time-using-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!