Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to a Single Date in Javascript

I have an input text that has a combination of date and time and display like this

04/01/2015 8:48PM 

How can i convert this string to a date using the function new Date() in javascript? not output is shown

Here is what i've tried so far, i can only convert the date not the time. HTML

 <form name="frm1" >


      <h3>Check in Date:</h3>
      <input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>

      <h3>Check out Date:</h3>
      <input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>

      <input type="button" onclick="computeDate()" value="Compute Difference" /> 

      <br><b>No of days: </b>
      <span id="date_difference"></span>

     </form>

JAVSCRIPT

function computeDate() {

        var dateTime1 = document.frm1.dtp1.value;
        var dateTime2 = document.frm1.dtp2.value;


        var startDate = new Date(dateTime1);
        var endDate = new Date(dateTime2);




        var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());

        if (timeDiff == 0) {
            timeDiff = 1;
        }

        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

        var total = parseFloat(diffDays) * parseFloat(roomRate);

        document.getElementById("date_difference").innerHTML = diffDays;
        document.getElementById("date_difference").style.visibility = "visible";

    }
like image 656
exol.exospazz Avatar asked Feb 27 '26 04:02

exol.exospazz


1 Answers

If the date format is always the same, create a convience function that converts the date to a Date object

function convert(date) {
    var dateArr = date.split(/[\s\/\:]/);

    if (dateArr[4].toLowerCase().indexOf('pm') != -1) 
        dateArr[3] = (+dateArr[3]) + 12;

    dateArr[4] = dateArr[4].replace(/\D/g,'');
    dateArr[0]--;

    return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}

FIDDLE

like image 64
adeneo Avatar answered Mar 01 '26 17:03

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!