JavaScript不会解析GMT日期/时间格式 [英] JavaScript won't parse GMT Date/Time Format

查看:133
本文介绍了JavaScript不会解析GMT日期/时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让JavaScript解析出我的日期和时间格式,最终的目的是告诉我自那天以来的时间和当地的时间(本地)。

I'm trying to get JavaScript to parse a date and time format for me, with the eventual aim of telling me the days passed since that date and the time right now (locally).

不幸的是,我必须使用的日期格式(来自我没有控制权的JSON响应)在2008-10-01 06返回:21:43格式。

Unfortunately, the date format I have to work with (it's from a JSON response which I don't have control over) is returning it in 2008-10-01 06:21:43 type format.

var thedate = "2008-10-01 06:21:43";
var inmillisecs = new Date(thedate);

这只是从JavaScript中返回错误,告诉我日期无效。

This just returns an error from JavaScript telling me the date is invalid.

如何解决这个问题?

推荐答案

应该这样做

function dateFromUTC( dateAsString, ymdDelimiter )
{
  var pattern = new RegExp( "(\\d{4})" + ymdDelimiter + "(\\d{2})" + ymdDelimiter + "(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})" );
  var parts = dateAsString.match( pattern );

  return new Date( Date.UTC(
      parseInt( parts[1] )
    , parseInt( parts[2], 10 ) - 1
    , parseInt( parts[3], 10 )
    , parseInt( parts[4], 10 )
    , parseInt( parts[5], 10 )
    , parseInt( parts[6], 10 )
    , 0
  ));
}

alert( dateFromUTC( "2008-10-01 06:21:43", '-' ) );

这篇关于JavaScript不会解析GMT日期/时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆