JavaScript倒数到MySQL datetime格式 [英] JavaScript countdown to MySQL datetime format
问题描述
我有一个来自MySQL数据库的日期,位于 datetime
格式中,像 2010-09-24 11:30:12
。我需要一种方式来显示几个小时的倒数时间:分钟到那个日期。
I have a date that comes from a MySQL database in the datetime
format, something like 2010-09-24 11:30:12
. And I need a way to show a countdown of hours:mins to that date.
我对JavaScript中的日期并不十分熟悉,所以任何帮助都将被忽略。谢谢。
I'm not very familiar with dates in JavaScript so any help would be apreciated. Thanks.
推荐答案
您可能想使用 UNIX_TIMESTAMP()
在 Unix时间格式(1970年1月1日以来的秒数)中返回日期。假设我们的目标日期是'2011-01-01 00:00:00'
(实际上你可能会有一个字段从你的表,而不是一个常量):
You may want to use the UNIX_TIMESTAMP()
function in MySQL to return your date in Unix Time Format (the number of seconds since January 1, 1970). Let's say our target date is '2011-01-01 00:00:00'
(in reality you would probably have a field from your table, instead of a constant):
SELECT UNIX_TIMESTAMP('2011-01-01 00:00:00') AS timestamp;
+---------------+
| timestamp |
+---------------+
| 1293836400 |
+---------------+
1 row in set (0.00 sec)
然后,我们可以使用 getTime()
方法中的 Date
对象在JavaScript中计算当前时间之间的秒数和目标时间。一旦我们有秒数,我们可以轻松计算出小时,分钟和天数:
Then we can use the getTime()
method of the Date
object in JavaScript to calculate the number of seconds between the current time and the target time. Once we have the number of seconds, we can easily calculate the hours, minutes and days:
var target = 1293836400; // We got this from MySQL
var now = new Date(); // The current tume
var seconds_remaining = target - (now.getTime() / 1000).toFixed(0);
var minutes_remaining = seconds_remaining / 60;
var hours_remaining = minutes_remaining / 60;
var days_remaining = hours_remaining / 24;
alert(seconds_remaining + ' seconds'); // 8422281 seconds
alert(minutes_remaining + ' minutes'); // 140371.35 minutes
alert(hours_remaining + ' hours'); // 2339.5225 hours
alert(days_remaining + ' days'); // 97.48010416666666 days
这篇关于JavaScript倒数到MySQL datetime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!