php - 我想得到在 php 表单中填写的两个时间戳之间的差异

标签 php mysql datetime datediff php-5.2

我有一个 HTML 表单,它将用户的数据作为 open_date 和 close_date。提交表单后,数据将被加载到 MYSQL 数据库中。

我想要的是: 我的数据库中有一个列,用于存储这两个时间戳之间的差异(以小时为单位)。

您能帮我找到解决方案吗?

最佳答案

功能

 function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Create temp time from time1 and interval
      $ttime = strtotime('+1 ' . $interval, $time1);
      // Set initial values
      $add = 1;
      $looped = 0;
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
        // Create new temp time from time1 and interval
        $add++;
        $ttime = strtotime("+" . $add . " " . $interval, $time1);
        $looped++;
      }

      $time1 = strtotime("+" . $looped . " " . $interval, $time1);
      $diffs[$interval] = $looped;
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
    break;
      }
      // Add value and interval 
      // if value is bigger than 0
      if ($value > 0) {
    // Add s if value is not 1
    if ($value != 1) {
      $interval .= "s";
    }
    // Add value and interval to times array
    $times[] = $value . " " . $interval;
    $count++;
      }
    }

    // Return string with times
    return implode(", ", $times);
  }

用法

echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";

该链接告诉您有关日期差异的所有信息

http://www.if-not-true-then-false.com/2010/php-calculate-real-differences-between-two-dates-or-timestamps/

关于php - 我想得到在 php 表单中填写的两个时间戳之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11097973/

相关文章:

php - html文本区域的白名单

php - 在 PHP 中压缩可以解码为原始形式的字符串的最佳方法

用于返回总排名的mysql查询

mysql - 在 mysql 中,有没有简单的方法可以知道错误/警告号的含义,而不是谷歌搜索

C# - 更新 SQL Server 中的日期时间列

过去 24 小时内最受欢迎的 PHP MySQL 查询

java - 比较java中表示时间戳的两种不同的UTC字符串格式

php - mysql 如果其他什么都不做

mysql - 将 MediaWiki 内容合并在一起

php - WooCommerce 在插件付款前获取订单产品详细信息