windows PHP日期计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/388673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP date calculation
提问by Marko
What is the best (date format independent way) in PHP to calculate difference in days between two dates in specified format.
PHP 中计算指定格式的两个日期之间的天数差异的最佳方式(日期格式独立方式)是什么。
I tried the following function:
我尝试了以下功能:
function get_date_offset($start_date, $end_date)
{
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
return round(($end_time-$start_time)/(3600*24));
}
It works ok on linux box, but when running under windows strtotime returns ''.
它在 linux box 上运行正常,但在 windows 下运行时 strtotime 返回 ''。
EDIT:
编辑:
Input date is in mm/dd/yyyyformat, but I would like to make it accept $format as a parameter.
输入日期采用mm/dd/yyyy格式,但我想让它接受 $format 作为参数。
I need only difference in days.
我只需要几天的差异。
回答by Irmantas
If you do not want or you cannot use Zend Framework or Pear package try this function i hope this would help:
如果您不想要或无法使用 Zend Framework 或 Pear 包,请尝试使用此功能,我希望这会有所帮助:
function dateDifference($date1, $date2)
{
$d1 = (is_string($date1) ? strtotime($date1) : $date1);
$d2 = (is_string($date2) ? strtotime($date2) : $date2);
$diff_secs = abs($d1 - $d2);
$base_year = min(date("Y", $d1), date("Y", $d2));
$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
return array
(
"years" => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
"months" => date("n", $diff) - 1,
"days_total" => floor($diff_secs / (3600 * 24)),
"days" => date("j", $diff) - 1,
"hours_total" => floor($diff_secs / 3600),
"hours" => date("G", $diff),
"minutes_total" => floor($diff_secs / 60),
"minutes" => (int) date("i", $diff),
"seconds_total" => $diff_secs,
"seconds" => (int) date("s", $diff)
);
}
回答by Rik Heywood
回答by Vilx-
The problem with PHP is that it doesn't have a definite DateTime type. You can use a Unix timestamp, or the built-in DateTime class, but they are pretty limited in their functionality. I expect that there should be some 3rd party classes with more extensive support for date-time calculations, but I haven't looked for it.
PHP 的问题在于它没有明确的 DateTime 类型。您可以使用 Unix 时间戳或内置的 DateTime 类,但它们的功能非常有限。我希望应该有一些 3rd 方类对日期时间计算提供更广泛的支持,但我还没有寻找它。
Using Unix timestamps for date (not time) calculations is also tricky. You'd have to discard the time part, but simply resetting to 00:00 is not safe because of daylight savings time (DST). DST has the effect that there are two days every year that don't have exactly 24 hours. Thus, when adding/subtracting dates you might end up with a value that does not divide evenly with 3600*24.
使用 Unix 时间戳进行日期(而不是时间)计算也很棘手。您必须放弃时间部分,但由于夏令时 (DST),简单地重置为 00:00 并不安全。DST 的影响是每年有两天不是 24 小时。因此,当添加/减去日期时,您可能会得到一个不能被 3600*24 平均划分的值。
I'd suggest looking for some 3rd party class that has proper support for all this stuff. Date/Time calculations are awesome in their ugliness. :P
我建议寻找一些对所有这些东西都有适当支持的 3rd 方课程。日期/时间计算的丑陋令人敬畏。:P
回答by Ole Helgesen
The Zend Framework has the class Zend_Datefor dealing with "date math". It works around system specific timestamp limits by using the BCMath extension, or if that's not available limits the timestamps by max float value for your system.
Zend 框架有一个Zend_Date类来处理“日期数学”。它通过使用 BCMath 扩展来解决系统特定的时间戳限制,或者如果它不可用,则通过系统的最大浮点值限制时间戳。
// example printing difference in days
require('Zend/Date.php');
$date1 = new Zend_Date();
$date1->set(2, Zend_Date::MONTH);
$date1->set(27, Zend_Date::DAY);
$date1->set(2008, Zend_Date::YEAR);
$date2 = new Zend_Date();
$date2->set(3, Zend_Date::MONTH);
$date2->set(3, Zend_Date::DAY);
$date2->set(2008, Zend_Date::YEAR);
echo ($date2->getTimestamp() - $date1->getTimestamp()) / (3600*24);
回答by csl
I'm not sure what is considered best, since there is no built-in function in PHP for doing this, but some people have used gregoriantojd(), for example in this forum post.
我不确定什么被认为是最好的,因为 PHP 中没有内置函数来执行此操作,但有些人使用了gregoriantojd(),例如在此论坛帖子中。
回答by Radek
gregoriantojd() gives the same results as using strtotime(), see this blogpost for how to do it:
gregoriantojd() 给出与使用 strtotime() 相同的结果,请参阅此博客文章了解如何操作:
回答by ftdysa
The following works for me. Believe I found it on the php.net docs somewhere.
以下对我有用。相信我在某个地方的 php.net 文档中找到了它。
*Edit - Woops, didn't see csl's post. This is the exact function from his link, must have been where I found it. ;)
*编辑 - 糟糕,没有看到 csl 的帖子。这是他链接中的确切功能,一定是我找到它的地方。;)
//Find the difference between two dates
function dateDiff($startDate, $endDate)
{
// Parse dates for conversion
$startArry = date_parse($startDate);
$endArry = date_parse($endDate);
// Convert dates to Julian Days
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
// Return difference
return round(($end_date - $start_date), 0);
}
回答by ivarne
I was trying to calculate the difference of two dates for the purpose of showing the duration of an event. Most of the functions given on the problem fails if the event has a duration form friday at 17:00 to sunday at 15:00. My goal was to find the difference between the dates like:
我试图计算两个日期的差异以显示事件的持续时间。如果事件的持续时间为星期五 17:00 至星期日 15:00,则针对该问题给出的大多数函数都会失败。我的目标是找到日期之间的差异,例如:
date('Ymd',$end)-date('Tmd',$begining);
But that is likly to fail because there isn't 99 month in a year and 99 days in a month. I could convert the date string to UNIX timestamp and divide by 60*60*12, but some days have a greater or lesser number of hours, sometimes there's eaven a leap secound. So I made my own function using getdate() a function that returns an array of innformation about the timestamp.
但这很可能会失败,因为一年没有 99 个月,一个月没有 99 天。我可以将日期字符串转换为 UNIX 时间戳并除以 60*60*12,但有些日子的小时数或多或少,有时甚至有一个闰秒。因此,我使用 getdate() 创建了自己的函数,该函数返回有关时间戳的信息数组。
/*
* datediff($first,$last)
* $first - unix timestamp or string aksepted by strtotime()
* $last - unix timestamp or string aksepted by strtotime()
*
* return - the difference in days betveen the two dates
*/
function datediff($first,$last){
$first = is_numeric($first) ? $first : strtotime($first);
$last = is_numeric($last ) ? $last : strtotime($last );
if ($last<$first){
// Can't calculate negative difference in dates
return -1;
}
$first = getdate($first);
$last = getdate($last );
// find the difference in days since the start of the year
$datediff = $last['yday'] - $first['yday'];
// if the years do not match add the appropriate number of days.
$yearCountedFrom = $first['year'];
while($last['year'] != $yearCountedFrom ){
// Take leap years into account
if( $yearCountedFrom % 4 == 0 && $yearCountedFrom != 1900 && $yearCountedFrom != 2100 ){
//leap year
$datediff += 366;
}else{
$datediff += 365;
}
$yearCountedFrom++;
}
return $datediff;
}
Concerning the GregorianToJD() function, it might work, but I feel a little bit uneasy since I do not understand how it work.
关于 GregorianToJD() 函数,它可能有效,但我觉得有点不安,因为我不明白它是如何工作的。
回答by James - Php Development
Calculate the difference between two Dates (and time) using Php. The following page provides a range of different methods (7 in total) for performing date / time calculations using Php, to determine the difference in time (hours, munites), days, months or years between two dates.
使用 PHP 计算两个日期(和时间)之间的差异。下一页提供了一系列不同的方法(总共 7 种),用于使用 Php 执行日期/时间计算,以确定两个日期之间的时间(小时、分钟)、天、月或年的差异。
See Php Date Time - 7 Methods to Calculate the Difference between 2 dates
回答by John Conde
PHP 5.2 introduces the DateTimeand DateIntervalclasses which makes this easy:
PHP 5.2 引入了DateTime和DateInterval类,这使得这很容易:
function get_date_offset($start_date, $end_date)
{
$start_time = new DateTime($start_date);
$end_time = new DateTime($end_date);
$interval = $end_time->diff($start_time);
return $interval->format('%a days');
}