为用户获取 2 个本地时间

Getting 2 Local Times for User

本文关键字:时间 用户 获取      更新时间:2023-09-26

例如,如果本地时间是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 分钟?

这应该足够了

<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

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>");