Search code examples
javascriptdatetimestring-to-datetime

how to convert string to valid date in javascript


I have time interval e.g. "01:30:00" as the string. Now I want to convert this string to a valid DateTime in javascript to manipulate. for example: add 1 hour.


Solution

  • I solved my problem.

    first Get current DateTime by new Date() second use .toDateString() third attach my time interval e.g. "01:30:00".

    new Date().toDateString() + ' ' + "01:30:00" // Mon May 09 2016 01:30:00
    

    Now use moment.js

    var t = moment(new Date().toDateString() + ' ' + "01:30:00");
    

    ّFinaly add for example 1 hour by moment().add()

    var finalTime = t.add(60, 'minutes').format("hh:mm");
    

    demo

    var stringTimeInterval = "01:30:00";
    
       var t = moment(new Date().toDateString() + ' ' + stringTimeInterval);
    
       document.getElementById("demo").innerHTML = t.add(60, 'minutes').format("hh:mm:00");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
    <div id="demo"></div>