英文:
How to get the difference between two date and times and show the time running down in Javascript
问题
我有两个变量。第一个变量从日期时间选择器中获取日期和时间值,第二个变量中获取当前日期和时间的值。现在我想要计算它们之间的差异,并在文本中显示像倒计时器一样的文字。
<input type="date" id="dates">
<input type="time" id="times">
var time=new Date().toLocaleTimeString('en-GB');
var res = time.slice(0,-3);
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
var current=today+" "+res; // 这里我获取当前日期和时间的值
var datetime=dates.value+" " +times.value; // 这个值来自日期时间选择器
var t = new Date(datetime) - new Date(current);
alert(t); // 这里输出的是时间差(毫秒)
我想要计算两个日期时间之间的差异并显示文本,类似于倒计时。
英文:
I have two variables i first variable I am getting the date and time value from date time picker and in second variable i am picking the value of current date and time. Now i want the difference between both of them and show in text like timer running down.
<input type="date" id="dates">
<input type="time" id="times">
var time=new Date().toLocaleTimeString('en-GB');
var res = time.slice(0,-3);
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
var current=today+" "+res; // Here i am getting the value of current date and time
var datetime=dates.value+" " +times.value; // This value is from date time picker
var t=datetime-current;
alert(t); //here the output is always NaN
I want the difference between both date times and show the text like timmer running down
答案1
得分: 0
根据假设的值更正了您的代码。
var dates = {
value: '2019-09-06'
};
var times = {
value: '10:55:00'
};
var time = new Date().toLocaleTimeString('en-GB');
var res = time.slice(0, -3);
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
var current = today + " " + res; // 这里获取当前日期和时间的值
var datetime = dates.value + " " + times.value; // 这个值来自日期时间选择器
var t = (new Date(datetime)).getTime() - (new Date(current)).getTime();
alert(t);
英文:
Corrected your code based on assumed values.
var dates = {
value: '2019-09-06'
};
var times = {
value: '10:55:00'
};
var time=new Date().toLocaleTimeString('en-GB');
var res = time.slice(0,-3);
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
var current=today+" "+res; // Here i am getting the value of current date and time
var datetime=dates.value+" " +times.value; // This value is from date time picker
var t= ( new Date( datetime ) ).getTime() - ( new Date( current ) ).getTime();
alert(t);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论