简体   繁体   中英

How convert input type="date" in timestamp javascript-jquery

I need to convert a in a timestamp, this is my html code:

 <input type="date" name="date_end" id="date_end">

This field has a value that I have put like 25/10/2017 My jquery code is:

var dataEnd = $('[name="date_end"]').val();
        if (!dataEnd) {
            return false;
        } else {
            var timestamp_end=$('[name="date_start"]').val().getTime();
            console.log("TIMESTAMP END "+timestamp_end);
.....
}

But this is not work, anyone can help me?

do this

var dateEnd = $('#date_end').val()
var var timestamp_end = Date.parse(date_end)

or in a single line

var timestamp_end = Date.parse($('#date_end').val())

it works and it's clean

make a new Date() passing the value of your input as parameter, then call getTime() . here an example:

 $('[name="date_end"]').on('change',function() { var dataEnd = $(this).val(); console.log((new Date(dataEnd)).getTime()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="date" name="date_end" id="date_end"> 

Here is a Solution ( Using pure js ) , I used the unary plus operator operator after converting the value into javascript date object.

 function checkDateValue(){ var dateConvertedToTimestamp = (+new Date(document.getElementById('date_value').value)); document.getElementById('date_value_timestamp').innerHTML = dateConvertedToTimestamp ; } 
 <input type='date' id='date_value'> <button onClick='checkDateValue()'> Submit </button> <div>Timestamp:- <span id='date_value_timestamp'></span></div> 

I needed an UNIX timestamp and updated Partha Roy's anwser for my needs.

Javascript :

  document.getElementById('dateInput').addEventListener('change', function (){
        
  let inputDate = document.getElementById('dateInput').value ;
  let dateConvertedToTimestamp = new Date(inputDate).getTime() ;
  console.log(dateConvertedToTimestamp) ;
  document.getElementById('resultTime').value = dateConvertedToTimestamp / 1000 ;
    }) ;

The /1000 division convert to UNIX timestamp + I track all input change and not only when the form is submited.

HTML :

<input type='date' id='dateInput'>
<input type='hidden' id='resultTime' name='dateTimestamp'>

Don't forget date input are still not well supported, so we can easily adapt this code with classic numbers input.

You can use following code

<script type="text/javascript">
var d = new Date(parseInt($('[name="date_start"]').val()));
var n = d.getTime();
console.log(n);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM