6

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?

4

5 回答 5

4

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">

于 2017-10-25T10:27:34.483 回答
3

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

于 2017-11-15T17:33:40.013 回答
1

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>

于 2017-10-25T10:27:35.767 回答
0

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.

于 2021-05-28T08:26:00.680 回答
-1

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>
于 2017-10-25T10:27:41.220 回答