'How convert input type="date" in a timestamp?
I need to convert an <input type="date">
value 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 working... why not?
Solution 1:[1]
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">
Solution 2:[2]
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
Solution 3:[3]
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>
Solution 4:[4]
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.
Solution 5:[5]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Roberto Bisello |
Solution 2 | |
Solution 3 | Partha Roy |
Solution 4 | Dharman |
Solution 5 | Jinesh |