Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

datetime - JavaScript won't parse GMT Date/Time Format

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).

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);

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

How do I get around this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should do it

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", '-' ) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...