Obtain milliseconds from date javascript

后端 未结 2 422
轮回少年
轮回少年 2021-01-07 02:13

I have a date format like this 2011-07-29T08:18:39

I want to convert this date intro milliseconds I try

var myDate = \'2011-07-29T08:18:39\';    
ne         


        
相关标签:
2条回答
  • 2021-01-07 02:52

    T.J. was correct; my original solution failed in IE9 and Safari. This will do it, and works in all major browsers.

    var myDate = '2011-07-29T08:18:39';    
    
    function parseDate(dateString){
        var time = Date.parse(dateString);
        if(!time){
            time = Date.parse(dateString.replace("T"," "));
            if(!time){
                bound = dateString.indexOf('T');
                var dateData = dateString.slice(0, bound).split('-');
                var timeData = dateString.slice(bound+1, -1).split(':');
    
                time = Date.UTC(dateData[0],dateData[1]-1,dateData[2],timeData[0],timeData[1],timeData[2]);
            }
        }
        return time;
    }
    
    var milliseconds = parseDate(myDate);
    
    0 讨论(0)
  • 2021-01-07 03:00

    The problem isn't getting the milliseconds (you're doing that right), it's getting the date.

    A lot of browsers still don't support that string format, including all released versions of IE, even IE9. That's because that ISO-8601-style format was only added to the specification in the 5th edition, about a year and a half ago; prior to that, the previous spec just said that they had to accept whatever Date#toString and Date#toUTCString spat out, and those were defined as "implementation-dependent" strings. E.g., you can't rely on their format. At all.

    Until the changes in the 5th edition spec are implemented more widely (and then several years go by until older browsers aren't still used by a significant fraction of the userbase), you'll have to parse the format yourself, or use something like DateJS to do it for you.

    DateJS is really very cool, but if you don't want to use it, parsing that format is dead easy provided your source is always giving you exactly that format (live copy):

    var myDate, parts, date, time, dt, ms;
    
    myDate = '2011-07-29T08:18:39';
    parts = myDate.split(/[T ]/); // Split on `T` or a space to get date and time
    date = parts[0];
    time = parts[1];
    
    dt = new Date();
    
    parts = date.split(/[-\/]/);  // Split date on - or /
    dt.setFullYear(parseInt(parts[0], 10));
    dt.setMonth(parseInt(parts[1], 10) - 1); // Months start at 0 in JS
    dt.setDate(parseInt(parts[2], 10));
    
    parts = time.split(/:/);    // Split time on :
    dt.setHours(parseInt(parts[0], 10));
    dt.setMinutes(parseInt(parts[1], 10));
    dt.setSeconds(parseInt(parts[2], 10));
    
    ms = dt.getTime(); // or ms = +dt; if you want to be l33t about it
    
    0 讨论(0)
提交回复
热议问题