如何在javascript中将给定的日期和时间转换为纪元时间?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在javascript中将给定的日期和时间转换为纪元时间?相关的知识,希望对你有一定的参考价值。
我试图将从UI获得的日期和时间转换为纪元时间。
请在下面找到我的代码。
function calculateEpoch(){
var date = 11/1/2019 //obtained from ui
var time = 11:00 //obtained from ui
var date1 = date +"" + time;
var someDate = new Date(date1);
console.log("someDate : ",someDate) //getting error like Invalid Date
someDate1 = someDate.getTime();
console.log("someDate : ",someDate1) //getting error like someDate1 is not defined
return someDate1 ;
}
有谁可以帮我解决工作代码。
答案
在" "
中添加""
instead of var date1 = date +" " + time;
它会起作用
function calculateEpoch(){
var date = '11/1/2019' //obtained from ui
var time = '11:00' //obtained from ui
var date1 = date +" " + time; // <---add space here
var someDate = new Date(date1);
console.log("someDate : ",someDate) //getting error like Invalid Date
someDate1 = someDate.getTime();
console.log("someDate : ",someDate1) //getting error like someDate1 is not defined
return someDate1 ;
}
另一答案
function calculateEpoch(){
var date = '11/1/2019' //obtained from ui
var time = '11:00' //obtained from ui
var date1 = `${date} ${time}`; // add a space in between the date and time,
// your date1 was invalid because it 11/1/2019:11:00
var someDate = new Date(date1);
console.log("someDate : ",someDate) //getting error like Invalid Date
someDate1 = someDate.getTime();
console.log("someDate : ",someDate1) //getting error like someDate1 is not defined
return someDate1 ;
}
希望这可以帮助
另一答案
你的前两行date
和time
是从ui获得的,所以我认为这不是问题所在。 (他们应该是字符串)
问题出在date1
上。
你有:11/1/201911:00
无效
应该是:11/1/2019 11:00
你几乎在那里,但你只需要在date
和time
之间添加一个空格。
function calculateEpoch(){
var date = '11/1/2019'; //obtained from ui
var time = '11:00'; //obtained from ui
var date1 = date + " " + time;
var someDate = new Date(date1);
console.log("someDate : ", someDate) //getting error like Invalid Date
someDate1 = someDate.getTime();
console.log("someDate : ", someDate1) //getting error like someDate1 is not defined
return someDate1;
}
calculateEpoch();
另一答案
这是一种方法,它与UI的连接和Date构造参数是显式的:
function calculateEpoch() {
var year = new Number(document.getElementById('uiYear').value);
var month = new Number(document.getElementById('uiMonth').value) - 1;
var day = new Number(document.getElementById('uiDay').value);
var hours = new Number(document.getElementById('uiHour').value);
var minutes = new Number(document.getElementById('uiMinute').value);
var seconds = new Number(document.getElementById('uiSecond').value);
var d = new Date(year, month, day, hours, minutes, seconds, 0);
var millis = d.getTime();
return millis
}
这个功能(在不同的名称下)实际上可以在右侧的https://currentmillis.com上与其UI一起使用。
请注意,此Date构造函数的month参数从零开始(1月为0,12月为11):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
以上是关于如何在javascript中将给定的日期和时间转换为纪元时间?的主要内容,如果未能解决你的问题,请参考以下文章