JavaScript won't parse GMT Date/Time Format

后端 未结 6 2074
我在风中等你
我在风中等你 2021-01-22 06:33

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

相关标签:
6条回答
  • 2021-01-22 07:20

    it must be a string that is recognizable by the parse() function.

    http://www.devguru.com/technologies/javascript/10585.asp look at the dateString param

    0 讨论(0)
  • 2021-01-22 07:23

    The correct syntax should be:

        var thedate = "Oct 1, 2008 06:21:43";
        var inmillisecs = new Date(thedate);
    

    You have to take some steps to transform the String you're receiving into the format I showed. Using the american format also works

       var thedate = "10/1/2008 06:21:42";
       var inmillisecs = new Date(thedate);
    
    0 讨论(0)
  • 2021-01-22 07:23

    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", '-' ) );
    
    0 讨论(0)
  • 2021-01-22 07:29

    The expected format is the American format: m/d/yyyy hh:mm:ss

    var date1 = new Date("2008-10-01 06:21:43"); //fails
    var date2 = new Date("10/1/2008 06:21:43"); //works correctly
    
    0 讨论(0)
  • 2021-01-22 07:30

    There's this nice looking library called DateJS. I have no experience with it, but you might find it useful. I think you'd be particularly interested in parse() and/or parseExact().

    I originally heard about it from this SO post.

    Cheers.

    EDIT: I just noticed your mention of time and I'm not sure DateJS handles times so I'm going to look into that real quick, or else you can just ignore this post :)

    0 讨论(0)
  • 2021-01-22 07:33

    That's an ISO 9601 date -- they're a nice standard to work with. Try just munging it using regular expressions:

    (\d{4})-(\d{2})-(\d{2})[ tT](.*)
    

    to

    \2/\3/\1 \4
    
    0 讨论(0)
提交回复
热议问题