如何解决Javascript倒计时特定日期/时间并重复
所以有一段时间我一直在尝试实现一个脚本,该脚本将剩余时间(倒计时)打印到一周中的特定日期(星期日)16 点(下午 4 点),我的服务器日期时区设置为 America/ New_York (GMT-5).. 到目前为止,我有这个代码,它不能正常工作,只有当倒计时剩余时间少于/低于 1 天时,脚本开始显示负值(例如,-1 小时 ..)任何帮助这里?干杯
https://jsfiddle.net/v4wjbtus/
function plural(s,i) {
return i + ' ' + (i > 1 ? s + 's' : s);
}
function sundayDelta(offset) {
// offset is in hours,so convert to miliseconds
offset = offset ? offset * 60 * 60 * 1000 : 0;
var now = new Date(new Date().getTime() + offset);
var days = 7 - now.getDay() || 7;
var hours = 21 - now.getHours() || 24;
var minutes = 60 - now.getMinutes();
var seconds = 60 - now.getSeconds();
return [plural('day',days),plural('hour',hours),plural('minute',minutes),plural('second',seconds)].join(' ');
}
// Save reference to the DIV
$refresh = jQuery('#refresh');
$refresh.text('News in ' + sundayDelta());
// Update DIV contents every second
setInterval(function() {
$refresh.text('News in ' + sundayDelta());
},1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="refresh" class="text-success" style="position: absolute;bottom: 0;"></div>
解决方法
由于已经有将毫秒持续时间转换为人类可读形式的示例,因此我使用您的代码和我发现的内容创建了一个混搭。
根据我的口味,我会进一步更新它,以便在分段等于零时不显示分段,以便更好地阅读。
// seed date,(ANY past sunday at 16:00)
var seed = new Date(2020,11,6,16);
var target;
// pluralize/singularize
function plural(s,i) {
return i + ' ' + (i > 1 ? s + 's' : s);
}
// miliseconds to the next upcoming sunday 16:00
function timeToTarget() {
while (seed < new Date()) {
seed.setDate(seed.getDate()+7)
}
target = seed;
return Math.abs(seed - new Date());
}
// convert miliseconds duration to human readable
function msReadableDuration() {
var duration = timeToTarget();
var seconds = Math.floor((duration / 1000) % 60),minutes = Math.floor((duration / (1000 * 60)) % 60),hours = Math.floor((duration / (1000 * 60 * 60)) % 24),days = Math.floor((duration / (24 * 60 * 60 * 1000) % 7));
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return [plural('day',days),plural('hour',hours),plural('minute',minutes),plural('second',seconds)].join(',');
}
// show seed date
$seed = jQuery('#seed');
$seed.text(seed.toString());
// Save reference to the DIV
$refresh = jQuery('#refresh');
$refresh.text('News in ' + msReadableDuration());
// Update DIV contents every second
setInterval(function() {
$refresh.text('News in ' + msReadableDuration());
},1000);
// show seed date (target is computed after timeToTarget executes)
$target = jQuery('#target');
$target.text(target.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="seed"></div>
<div id="target"></div>
<p id="refresh"></p>
而不是使用种子日期,您可以进一步优化我的代码段,使其具有一个函数,该函数通过类似于以下内容的内容简单地查找下一个即将到来的星期日:https://codereview.stackexchange.com/a/33648
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。