strtotime:检查时间

strtotime: Check for time

我有一个凭证系统,我可以在其中输入日期或带时间的日期。应该允许所有有效格式,例如:

这没问题,如果我有凭证的开始日期,但如果我有结束日期[=44=,那就有问题了].我使用 strtotime 将用户输入转换为 UNIX 时间戳。

如果您只输入日期结束日期,它应该是使用的一天的结束。像这样:

01.01.2016 -> 01.01.2016 23:59:59 -> 1451689199

但是 - 这是我的问题 - strtotime returns 01.01.201601.01.2016 00:00:00 当然是相同的时间戳。而当用户输入一个时间,当然要使用这个时间。

01.01.2016
1451602800
-> should go to 1451689199

01.01.2016 00:00:00
1451602800
-> is correct

01.01.2016 23:59:59
1451689199
-> is correct

我需要检查由 strtotime 转换的字符串是否有明确的时间。我为此搜索了一个函数但没有成功,即使 DateTime class 也没有这个方法(hasTime() 或类似的东西)。

正如我之前所说,所有 date/time 格式 strtotime 支持也应该被此功能支持。

这个问题不是重复的!我想检查是否有明确指定的时间。应该重复的问题是PHP初学者的基础问题,与本题完全无关!

给定输入 '2015031''2015031 10:39',你基本上可以尝试第一个,如果 returns 错误,请尝试另一个。

尽管无法保证稳健性

php > var_dump(DateTime::createFromFormat('Ymd H:s','2015031'));
 bool(false)
php > var_dump(DateTime::createFromFormat('Ymd H:s','2015031 10:29'));
 object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2015-03-01 10:00:29.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

显然根据您的需要更改格式并使用 ->getTimestamp 提取 TS。

我会在调用 strtotime 之前测试字符串的长度并添加 23:59:59:

$dates = array('01.01.2016','01.01.2016 23:59:59','01.01.2016 10:25:30');
foreach($dates as $date) {
    echo "date=$date\n";
    if (strlen($date) > 10) {
        echo strtotime($date),"\n";
    } else {
        echo strtotime($date . ' 23:59:59'),"\n";
    }
}

输出:

date=01.01.2016
1451689199
date=01.01.2016 23:59:59
1451689199
date=01.01.2016 10:25:30
1451640330

根据您提供的时间戳判断,作为输入的 unix 纪元转换都是 GMT 时间。如果是这种情况,您可以尝试使用 gmdate 函数对明确设置的时间进行基本检查,并假设如果它们有值,则它是用户修改的时间戳。

如果不是,可以修改时间戳,在日期上加上23小时59分59秒的余量。

<?php
  $unixstamp = '1451520000'; // Thu, 31 Dec 2015 00:00:00 GMT
  $day = gmdate( 'Y-m-d', $unixstamp ); // 2015-12-31
  $hour = (int)gmdate( 'H', $unixstamp); // 0
  $minute = (int)gmdate( 'i', $unixstamp ); // 0 

  //check if hours or minutes have been set explicitly 
 if( $hour > 0 || $minute > 0 ){
   //User Modified Time
   echo gmdate("c",$unixstamp);

 } else {
   //here add the 23 hours and 59 minutes on and return as date object
   echo gmdate("c", strtotime('+23 hours + 59 minutes + 59 seconds', $unixstamp));  

   //here add the 23 hours and 59 minutes on and return as unix epoch timestamp
   $endofday = gmdate("U", strtotime('+23 hours + 59 minutes + 59 seconds', $unixstamp));   
 }
?>

时区绝对是一个考虑因素,但上面的代码将检查 GMT unix 时间戳以明确设置时间。

默认所有时间戳都包含时间,即使不设置也是00:00:00.

所以在这种情况下,您可以这样做:

<?php 

$notime = 1420070400;
$withtime = 1420110000;


$time = date("H:i:s", $withtime);

if($time == "00:00:00") {
    echo "time not set";
} else {
    echo "time set";
}

?>