如何使用PHP和MySQL显示时间倒计时

时间:2022-10-29 08:11:55

How do I get a time countdown using PHP?

如何使用PHP进行时间倒计时?

I want to display something like 3Days 4Hours. I have a date field coming from MySQL table and want to calculate it with today's date. As of now I have only date and not the time stored in the database, but eventually I will. So at that time, I might show as 3Days 4Hours 10Minutes 43seconds.

我想要显示3天4小时。我有一个来自MySQL表的日期字段,我想用今天的日期来计算它。到目前为止,我只有日期,而没有存储在数据库中的时间,但最终我会。所以在那个时候,我可能会显示3天4小时10分43秒。

This is what I tried but am getting some wrong answer:

这是我试过的,但我得到了一个错误的答案:

$datetime1 = new DateTime($starton);//$starton - date stored in db
$datetime2 = new DateTime(date());
$interval = $datetime1->diff($datetime2);
echo $interval->format('%d days);

I am confused if this works based of server time or the zone where the user is coming from. Please guide me. When I have the time field, I guess I might need jQuery to show the seconds live and so the minutes too.

我很困惑,这是基于服务器时间还是用户来自的区域。请指导我。当我有时间字段时,我想我可能需要jQuery来显示秒和分钟。

6 个解决方案

#1


3  

IMHO when you are thinking about comparing time, you automatically start talking Unix time. Essentially, Unix time is a count in seconds that always increments. When you have 2 Unix timestamps, then you can use simple arithmetic to figure the difference and then translate the difference into human readable form.

当您考虑比较时间时,您会自动地开始讨论Unix时间。从本质上说,Unix时间是秒数,总是递增的。当您有两个Unix时间戳时,您可以使用简单的算术来计算差异,然后将差异转换为人类可读的形式。

Note that Unix timestamps are common in almost all programming languages, so you can choose whether to do this in PHP, MySQL or JavaScript and it could all turn out the same way. I'll show you the PHP version.

请注意,Unix时间戳在几乎所有编程语言中都是常见的,因此您可以选择是使用PHP、MySQL还是JavaScript进行这种操作,结果都是相同的。我将展示PHP版本。

So you want to do this:

你想这样做:

  1. Find the Unix timestamp for your target event
  2. 查找目标事件的Unix时间戳
  3. Store that in the MySQL database
  4. 存储在MySQL数据库中
  5. Retrieve from the database
  6. 从数据库中检索
  7. Get current Unix timestamp
  8. 得到当前Unix时间戳
  9. Subtract to get difference
  10. 减去得到不同
  11. Multiply/divide to get human readable format
  12. 乘/除可以得到人类可读的格式

The PHP code:

PHP代码:

//Unix timestamp to Dec. 21, 2012 (midnight)
$unix_time = mktime(0,0,0,12,21,2012); 
//Connect to MySQL
//"INSERT INTO table (target_timestamp) VALUES ($unix_time);"


//----- user goes to page -----
//Connect to MySQL
$sql = "SELECT target_timestamp FROM table WHERE foo = bar";
$unix_time = do_query($sql);//do_query not defined, assume it gets the timestamp
$current_time = time();
$diff = $unix_time - $current_time
//$diff should be positive and not 0
if( 1 > $diff ){
   exit('Target Event Already Passed (or is passing this very instant)');
} else {
   $w = $diff / 86400 / 7;
   $d = $diff / 86400 % 7;
   $h = $diff / 3600 % 24;
   $m = $diff / 60 % 60; 
   $s = $diff % 60;

   return "{$w} weeks, {$d} days, {$h} hours, {$m} minutes and {$s} secs away!"
}

#2


1  

PHP will use the timezone set by the server, which can be manually set in your script using date_default_timezone_set(). You can do this a couple ways:

PHP将使用服务器设置的时区,可以使用date_default_timezone_set()在脚本中手动设置该时区。你可以用以下几种方法:

You can actually use your MySQL query to do the calculation for you. See the TimeDiff() function: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timediff. Then, you can use TimeFormat() to format it as how you want it.

您可以使用MySQL查询为您进行计算。查看TimeDiff()函数:http://dev.mysql.com/doc/refman/5.1/en/dateandtimefunctions.html #function_timediff。然后,您可以使用TimeFormat()按自己的方式对其进行格式化。

Alternatively you can do it through PHP. You can either convert to unix epoch -> format as a date. The other option would be to start with two DateTime objects as you have done. Try:

也可以通过PHP来实现。您可以转换为unix纪元->格式作为日期。另一种选择是从两个DateTime对象开始。试一试:

$datetime1 = new DateTime($starton);
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%d days);

Or procedurally:

或过程:

$datetime1 = date_create($starton);
$datetime2 = date();
$interval = date_diff($datetime1,$datetime2);
echo $interval->format('%d days');

Also, if you want to display the counter as a real-time updating counter; you'll probably have to hand this over to a Javascript function later.

另外,如果您想将计数器显示为实时更新计数器;您可能需要稍后将其交给Javascript函数。

#3


1  

Since you mentioned jQuery, it is possible to do it just by JavaScript if that's ok with you.

既然您提到了jQuery,那么如果您觉得可以的话,可以通过JavaScript来实现。

jQuery countdown plugin and working example: http://keith-wood.name/countdown.html

jQuery倒计时插件和工作示例:http://keith-wood.name/countdown.html。

Will save you making calls to your db also.

将节省你打电话给你的数据库也。

#4


0  

Not 100% answering your question, but a manual way to do it would be this:

不是百分之百的回答你的问题,但是手工的方法是:

$start = strtotime($dbTime);
$now = time();
$differenceInSeconds = $start - $now;

From there you just need to format it, and you can find an algorithm in this answer.

从那里你只需要格式化它,你可以在这个答案中找到一个算法。

#5


0  

Well, I think if you're calling date() on the server, you're going to get the server date and time zone. You can force the timezone with the function date_default_timezone_set([TIMEZONE]);, though, if that's a concern.

我认为如果您在服务器上调用date(),您将获得服务器日期和时区。您可以使用函数date_default_timezone_set([timezone])强制时区;但是,如果这是一个问题的话。

If I were doing this, and wanted a second-by-second countdown, I'd probably pass the calculated interval to javascript and let jQuery do the formatting, particularly if you want an active counter.

如果我这样做,并且想要一秒一秒地倒数,我可能会将计算的时间间隔传递给javascript并让jQuery进行格式化,特别是如果您想要一个活动计数器的话。

For that matter, you could offload the whole thing to javascript, and pass it the two dates, and use date1.getTime() - date2.getTime() to get the time difference in milliseconds, and do the math yourself in javascript (this is cribbed from this answer)

因此,您可以将整个内容卸载到javascript,并将两个日期传递给它,并使用date1.getTime() - date2.getTime(

That's probably how I would do it, if I were altering it in JS anyway.

这可能就是我要做的,如果我用JS修改的话。

#6


0  

This is a solution that some frameworks (like Ruby on Rails) has tackled, PHP doesn't appear to be one of them, I think what you are looking for is something like:

这是一些框架(如Ruby on Rails)已经解决的解决方案,PHP似乎不是其中之一,我认为您需要的是以下内容:

http://www.phpro.org/examples/Convert-Seconds-To-Hours-Minutes-Seconds-Words.html

http://www.phpro.org/examples/Convert-Seconds-To-Hours-Minutes-Seconds-Words.html

#1


3  

IMHO when you are thinking about comparing time, you automatically start talking Unix time. Essentially, Unix time is a count in seconds that always increments. When you have 2 Unix timestamps, then you can use simple arithmetic to figure the difference and then translate the difference into human readable form.

当您考虑比较时间时,您会自动地开始讨论Unix时间。从本质上说,Unix时间是秒数,总是递增的。当您有两个Unix时间戳时,您可以使用简单的算术来计算差异,然后将差异转换为人类可读的形式。

Note that Unix timestamps are common in almost all programming languages, so you can choose whether to do this in PHP, MySQL or JavaScript and it could all turn out the same way. I'll show you the PHP version.

请注意,Unix时间戳在几乎所有编程语言中都是常见的,因此您可以选择是使用PHP、MySQL还是JavaScript进行这种操作,结果都是相同的。我将展示PHP版本。

So you want to do this:

你想这样做:

  1. Find the Unix timestamp for your target event
  2. 查找目标事件的Unix时间戳
  3. Store that in the MySQL database
  4. 存储在MySQL数据库中
  5. Retrieve from the database
  6. 从数据库中检索
  7. Get current Unix timestamp
  8. 得到当前Unix时间戳
  9. Subtract to get difference
  10. 减去得到不同
  11. Multiply/divide to get human readable format
  12. 乘/除可以得到人类可读的格式

The PHP code:

PHP代码:

//Unix timestamp to Dec. 21, 2012 (midnight)
$unix_time = mktime(0,0,0,12,21,2012); 
//Connect to MySQL
//"INSERT INTO table (target_timestamp) VALUES ($unix_time);"


//----- user goes to page -----
//Connect to MySQL
$sql = "SELECT target_timestamp FROM table WHERE foo = bar";
$unix_time = do_query($sql);//do_query not defined, assume it gets the timestamp
$current_time = time();
$diff = $unix_time - $current_time
//$diff should be positive and not 0
if( 1 > $diff ){
   exit('Target Event Already Passed (or is passing this very instant)');
} else {
   $w = $diff / 86400 / 7;
   $d = $diff / 86400 % 7;
   $h = $diff / 3600 % 24;
   $m = $diff / 60 % 60; 
   $s = $diff % 60;

   return "{$w} weeks, {$d} days, {$h} hours, {$m} minutes and {$s} secs away!"
}

#2


1  

PHP will use the timezone set by the server, which can be manually set in your script using date_default_timezone_set(). You can do this a couple ways:

PHP将使用服务器设置的时区,可以使用date_default_timezone_set()在脚本中手动设置该时区。你可以用以下几种方法:

You can actually use your MySQL query to do the calculation for you. See the TimeDiff() function: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timediff. Then, you can use TimeFormat() to format it as how you want it.

您可以使用MySQL查询为您进行计算。查看TimeDiff()函数:http://dev.mysql.com/doc/refman/5.1/en/dateandtimefunctions.html #function_timediff。然后,您可以使用TimeFormat()按自己的方式对其进行格式化。

Alternatively you can do it through PHP. You can either convert to unix epoch -> format as a date. The other option would be to start with two DateTime objects as you have done. Try:

也可以通过PHP来实现。您可以转换为unix纪元->格式作为日期。另一种选择是从两个DateTime对象开始。试一试:

$datetime1 = new DateTime($starton);
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%d days);

Or procedurally:

或过程:

$datetime1 = date_create($starton);
$datetime2 = date();
$interval = date_diff($datetime1,$datetime2);
echo $interval->format('%d days');

Also, if you want to display the counter as a real-time updating counter; you'll probably have to hand this over to a Javascript function later.

另外,如果您想将计数器显示为实时更新计数器;您可能需要稍后将其交给Javascript函数。

#3


1  

Since you mentioned jQuery, it is possible to do it just by JavaScript if that's ok with you.

既然您提到了jQuery,那么如果您觉得可以的话,可以通过JavaScript来实现。

jQuery countdown plugin and working example: http://keith-wood.name/countdown.html

jQuery倒计时插件和工作示例:http://keith-wood.name/countdown.html。

Will save you making calls to your db also.

将节省你打电话给你的数据库也。

#4


0  

Not 100% answering your question, but a manual way to do it would be this:

不是百分之百的回答你的问题,但是手工的方法是:

$start = strtotime($dbTime);
$now = time();
$differenceInSeconds = $start - $now;

From there you just need to format it, and you can find an algorithm in this answer.

从那里你只需要格式化它,你可以在这个答案中找到一个算法。

#5


0  

Well, I think if you're calling date() on the server, you're going to get the server date and time zone. You can force the timezone with the function date_default_timezone_set([TIMEZONE]);, though, if that's a concern.

我认为如果您在服务器上调用date(),您将获得服务器日期和时区。您可以使用函数date_default_timezone_set([timezone])强制时区;但是,如果这是一个问题的话。

If I were doing this, and wanted a second-by-second countdown, I'd probably pass the calculated interval to javascript and let jQuery do the formatting, particularly if you want an active counter.

如果我这样做,并且想要一秒一秒地倒数,我可能会将计算的时间间隔传递给javascript并让jQuery进行格式化,特别是如果您想要一个活动计数器的话。

For that matter, you could offload the whole thing to javascript, and pass it the two dates, and use date1.getTime() - date2.getTime() to get the time difference in milliseconds, and do the math yourself in javascript (this is cribbed from this answer)

因此,您可以将整个内容卸载到javascript,并将两个日期传递给它,并使用date1.getTime() - date2.getTime(

That's probably how I would do it, if I were altering it in JS anyway.

这可能就是我要做的,如果我用JS修改的话。

#6


0  

This is a solution that some frameworks (like Ruby on Rails) has tackled, PHP doesn't appear to be one of them, I think what you are looking for is something like:

这是一些框架(如Ruby on Rails)已经解决的解决方案,PHP似乎不是其中之一,我认为您需要的是以下内容:

http://www.phpro.org/examples/Convert-Seconds-To-Hours-Minutes-Seconds-Words.html

http://www.phpro.org/examples/Convert-Seconds-To-Hours-Minutes-Seconds-Words.html