我要做的是,例如,如果当地时间是6:00PM
我想提前10分钟显示时间6:10PM
,而另一次我希望从当前时间回来50分钟,这将是5:10PM
..我到目前为止所做的事情都没有,因为我只能弄清楚如何显示当前时间
<script>
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
</script>
我如何回到50分钟并提前10分钟?
答案 0 :(得分:1)
这应该足够了
<script>
var futureTime = new Date();
futureTime.setMinutes(futureTime.getMinutes()+10);
var pastTime = new Date();
pastTime.setMinutes(pastTime.getMinutes()-50);
</script>
然后只需将pastTime和futureTime变量与现有的显示代码一起使用。
来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
答案 1 :(得分:0)
function formatDate(d)
{
var hours = d.getHours();
var minutes = d.getMinutes();
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
{
minutes = "0" + minutes;
}
return hours + ":" + minutes + " " + suffix;
}
var currentTime = new Date();
var futureTime = new Date(currentTime.getTime());
futureTime.setMinutes(futureTime.getMinutes() + 10);
var pastTime = new Date(currentTime.getTime());
pastTime.setMinutes(pastTime.getMinutes() - 50);
document.write("<b>" + formatDate(currentTime) + "</b>");
document.write("<b>" + formatDate(futureTime) + "</b>");
document.write("<b>" + formatDate(pastTime) + "</b>");