How can I convert a HH:mm:ss string to a JavaScript Date object?

前端 未结 3 1577
温柔的废话
温柔的废话 2020-12-17 01:55

I have dynamic string with a HH:mm:ss format (e.g. 18:19:02). How can the string be converted into a JavaScript Date object (in Internet Explorer 8

相关标签:
3条回答
  • 2020-12-17 02:20

    Try this (without jQuery and a date object (it's only a time)):

    var
        pieces = "8:19:02".split(':')
        hour, minute, second;
    
    if(pieces.length === 3) {
        hour = parseInt(pieces[0], 10);
        minute = parseInt(pieces[1], 10);
        second = parseInt(pieces[2], 10);
    }
    
    0 讨论(0)
  • 2020-12-17 02:21

    The Date object is never properly set because of the missing date part. This should work:

    var d = new Date("1970-01-01 18:19:02");
    document.write(d.getMinutes() + ":" + d.getSeconds());
    
    0 讨论(0)
  • 2020-12-17 02:31

    You cannot create a Date Object directly just from a time like HH:mm:ss.

    However - assuming you want the actual date(day) or it doesn't matter for your case - you could do the following:

    let d = new Date(); // Creates a Date Object using the clients current time
    
    let [hours, minutes, seconds] = "18:19:02".split(':'); // Using ES6 destructuring
    // var time = "18:19:02".split(':'); // "Old" ES5 version
    
    d.setHours(+hours); // Set the hours, using implicit type coercion
    d.setMinutes(minutes); // You can pass Number or String. It doesn't really matter
    d.setSeconds(seconds);
    // If needed, adjust date and time zone
    
    console.log(d.toString()); // Outputs your desired time (+current day and timezone)

    Now you have a Date object which contains the time you specified plus the current date and timezone of your client.

    0 讨论(0)
提交回复
热议问题