如何在javascript中添加小时和分钟 [英] How to add hour and minute in javascript
问题描述
我想在当前时间添加小时和小时。例如现在时间是下午2:00如果我输入20:00它将改变不仅在同一时间日期的时间也被改变。如何我完成了这个吗?
我尝试了什么:
i尝试过很多方法但却无法做到
i want to add hour and minit to current time.for example right now time is 2:00 PM if i give input 20:00 it will change not only the time at the same time date is also be changed.how can i accomplish this?
What I have tried:
i have tried many ways but couldnot do that
推荐答案
标题比你的问题更清晰。所以我将回答标题。
首先,关于JavaScript DateTime的相关参考文献在这里:
1. JavaScript日期 [ ^ ]
2. JavaScript日期格式 [ ^ ]
3. JavaScript日期方法 [ ^ ]
在我的解释和示例代码如下所示后,请仔细阅读。
首先,转换任何日期时间组件以毫秒为单位,包括间隔;
其次,使用毫秒执行任何所需的算术运算;
最后,转换结果m回到新的日期时间。
研究充分评论的示例代码:
The title is clearer than your question. So I will answer to the title.
First thing first, the relevant references on JavaScript DateTime are here:
1. JavaScript Dates[^]
2 .JavaScript Date Formats[^]
3. JavaScript Date Methods[^]
Do go through them after my explanation and example code shown below.
First, convert any date time components into milliseconds, including the interval;
Second, perform any desired arithmetic calculation using the milliseconds;
Lastly, convert the resulting milliseconds back to the new date time.
Study the example code which is adequately commented:
<!DOCTYPE html>
<html>
<body>
<p id="startDateTime"></p>
<p id="futureDateTime"></p>
<script>
var startDateTime = new Date(2017,0,2,12,30,00,0);
document.getElementById("startDateTime").innerHTML = startDateTime;
// convert the startDate into milliseconds
var startDateTimeInMilliseconds = startDateTime.getTime();
// what is the date time 12 hours 30 minutes away?
// change the 12 hours to milliseconds
var hoursInMilliseconds = 12*60*60*1000; // milliseconds
// likewise, change the 30 minutes to milliseconds
var minutesInMilliseconds = 30*60*1000; // milliseconds
// the future date in milliseconds is
var futureInMilliseconds = startDateTimeInMilliseconds + hoursInMilliseconds + minutesInMilliseconds;
// convert milliseconds to date time
var futureDateTime = new Date(futureInMilliseconds);
document.getElementById("futureDateTime").innerHTML = futureDateTime;
</script>
</body>
</html>
JSFiddle 的演示版[ ^ ]
使用以上链接进行交叉引用,以便更好地了解我的代码。
A demo version at JSFiddle[^]
Cross-referencing with the above links to better understand my code.
如果你想为一个日期添加一个时间段,你基本上必须将它们都转换成毫秒。
这是一个解决问题的链接。
[ ^ ]
If you want to add a time period to a date, you basically have to convert both of them into milliseconds.
Here is a link to solve your problem.
Add two dates times together in javascript - Stack Overflow[^]
我尝试了很多方法但是不能那样做
i have tried many ways but could not do that
主要有1种方法。
搜索DateTim e数据类型和学习相关的功能。
Goolgle是你的朋友。
There is mainly 1 single way.
Search about DateTime datatype and study associated functions.
Goolgle is your friend.
这篇关于如何在javascript中添加小时和分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!