使用UTC以小时,分钟,秒为单位获取JavaScript中两个日期之间的时差 [英] Getting the difference between 2 dates in Javascript in hours, minutes, seconds with UTC

查看:59
本文介绍了使用UTC以小时,分钟,秒为单位获取JavaScript中两个日期之间的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题中所说的,我需要获取两个日期之间的差,并显示倒计时到完成日期的小时,分​​钟和秒。我有这个:

Like the title says, I need to get the difference between two dates and display the hours, minutes, seconds that counts down to the finish date. I have this:

function timer(){
	
	'use strict'
	
	var date1 = new Date().getTime();
	var date2 = new Date("05/29/2017").getTime();
	
	var diff = date2 - date1;
	
	var seconds = diff / 1000;
	var minutes = (diff / 1000) / 60;
	var hours = minutes / 60;

	var message = 'Hours: ' + Math.floor(hours) + " Minutes: " + Math.floor(minutes) + " Seconds: " + Math.floor(seconds); 
	
	var output = document.getElementById('output');
	if (output.textContent !== undefined) {
		output.textContent = message;
	} else {
		output.innerText = message;
	}
}
setInterval("timer()", 1000);
window.onload = timer;

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>hi</title>
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link rel="stylesheet" href="css/form.css">
</head>
<body>
    <!-- auction.html -->
    <form action="#" method="post" id="theForm">
        <fieldset><legend>Auction ends on May 29, 2017</legend>
		    <p>Refresh page for updated times.</p>
			<div id="output"></div>
            <input type="submit" value="Refresh" id="submit">
        </fieldset>
    </form>
    <script src="js/auction.js"></script>
</body>
</html>

>

我的作业说明指出,我需要:选择将来的结束日期(应在作业分配后的几周内)并使用UTC。显示小时数,距拍卖结束还剩几分钟和几秒钟。
我有点不知道如何实施UTC和创建适当的倒计时?我什至不确定自己是否做对了(我才刚刚开始学习j.s)。我应该如何修正我的代码?

The instructions for my assignment state that I need to: "Choose an end date in the future (several weeks after assignment is due) and use UTC. Display the hours, minutes, and seconds left until the auction ends." I'm kind of lost on how to implement the UTC and create a proper countdown? I'm not even sure if I did any of it right (I am just starting to learn j.s). How should I fix my code?

推荐答案

在您的代码中,您有:

var date1 = new Date().getTime();

在这种情况下,无需使用 getTime 。但是使用有意义的变量名会有所帮助:

There's no need to use getTime in this case. But it is helpful to use meaningful variable names:

var now = new Date();

然后是:

var date2 = new Date("05/29/2017").getTime();

不要使用Date构造函数(或Date.parse)来解析字符串,因为它主要取决于实现并不一致。如果您有特定的日期,则将值直接传递给构造函数。

Don't use the Date constructor (or Date.parse) to parse strings as it's mostly implementation dependent and inconsistent. If you have a specific date, pass values directly to the constructor.

关于 使用UTC ,这有点令人困惑,因为ECMAScript Date对象是UTC。他们使用主机时区偏移量来计算内部UTC时间值,并显示本地日期和时间值。我可以解释使用UTC的唯一方法是使用Date.UTC创建日期实例,例如:

Regarding "use UTC", that's a bit confusing as ECMAScript Date objects are UTC. They use the host timezone offset to calculate an internal UTC time value, and also to display "local" date and time values. The only way I can interpret "use UTC" is to use Date.UTC to create a date instance, e.g.:

var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z

现在,您可以获得现在和现在之间的区别使用:

Now you can get the difference between then an now using:

var diff = endDate - now; 

尝试获取小时,分钟和秒时,您将:

When trying to get the hours, minutes and seconds you have:

var seconds = diff / 1000;
var minutes = (diff / 1000) / 60;
var hours = minutes / 60;

将全部差异转换为小时,分钟和秒,因此总时间约为3倍应该是什么。您只需要这些组件,所以:

That converts the entire difference to each of hours, minutes and seconds so the total time is about 3 times what it should be. What you need is just the components, so:

var hours = Math.floor(diff / 3.6e5);
var minutes = Math.floor(diff % 3.6e5) / 6e4);
var seconds = Math.floor(diff % 6e4) / 1000;

将它们全部整合到一个函数中:

Putting it all together in one function:

function timeLeft() {
    var now = new Date();
    var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z
    var diff = endDate - now; 

    var hours   = Math.floor(diff / 3.6e6);
    var minutes = Math.floor((diff % 3.6e6) / 6e4);
    var seconds = Math.floor((diff % 6e4) / 1000);
    console.log('Time remaining to ' + endDate.toISOString() + 
                ' or\n' + endDate.toString() + ' local is\n' +
                 hours + ' hours, ' +  minutes + ' minutes and ' + 
                 seconds + ' seconds');
}

timeLeft()

有关于计时器和日期差异,这里有很多很多问题和答案,请进行一些搜索。

There are many, many questions and answers here about timers and date differences, do some searches.

这篇关于使用UTC以小时,分钟,秒为单位获取JavaScript中两个日期之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆