[英]How convert input type="date" in timestamp javascript-jquery
I need to convert a in a timestamp, this is my html code:我需要在时间戳中转换 a,这是我的 html 代码:
<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:这个字段有一个值,我把它放在 25/10/2017 我的 jquery 代码是:
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()
. 创建一个新的
Date()
,将输入值作为参数传递,然后调用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. 这是一个解决方案(使用纯js),在将值转换为javascript date对象之后,我使用了一元加运算符。
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.我需要一个 UNIX 时间戳并根据我的需要更新了 Partha Roy 的 anwser。
Javascript : 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. /1000 除法转换为 UNIX 时间戳 + 我跟踪所有输入更改,而不仅仅是在提交表单时。
HTML : 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.