【问题标题】:Calculate YEAR of a past date without YEAR in PHP在 PHP 中计算没有 YEAR 的过去日期的 YEAR
【发布时间】:2018-03-26 15:24:57
【问题描述】:

我从不包含年份的日志文件中提取日期。 唯一已知的事实是日期已过去。可能是 1 秒前,但不超过 365 天前。

我喜欢计算年份。

日志文件日期格式是

date('m-d H:i:s');

如果当前日期是“2018 年 4 月 1 日”, 日志文件“1 Jan”将是“1 Jan 2018”。

但是当日志文件日期读取时

'20 Dec'  I need '20 Dec 2017'
'2 Apr'   I need  '2 Apr 2017' (as 2 Apr 2018 would be in the future)
'1 Apr'   I need  '1 Apr 2018' (that's today)

【问题讨论】:

  • 向我们展示您的尝试。
  • 创建日期,并检查日期是否高于当前日期。如果是,则从中减去一年。
  • 闰年和夏令时的特殊情况祝你好运

标签: php date datetime


【解决方案1】:

我建议使用这个 sn-p 作为起点:

$today = date('m-d H:i:s');
$dates = array(
    '04-20 15:00:00',
    '02-03 15:00:00',
    '05-12 15:00:00',
    '01-14 15:00:00',
    '02-15 15:00:00',
);

echo $today.'<br>';

foreach($dates as &$date) {
    $exploded = explode(' ',$date);
    if($date > $today) {
        $date = $exploded[0].'-2017 '.$exploded[1];
        echo $date . '<br>';
    } else {
        $date = $exploded[0].'-2018 '.$exploded[1];
        echo $date . '<br>';
    }
}

它应该输出如下内容:

03-26 11:49:33

04-20-2017 15:00:00

02-03-2018 15:00:00

05-12-2017 15:00:00

01-14-2018 15:00:00

02-15-2018 15:00:00

【讨论】:

  • 我很确定将 01-14 15:00:00 之类的内容与 Unix 时间戳进行比较不会特别可靠...
  • 我认为这不会成为问题,因为今天的日期是在没有年份的情况下生成的,因此可以进行比较
  • 并不是因为 Unix 时间戳(正如您从 date() 得到的那样)特别是自 1970 年 1 月 1 日午夜以来的秒数 - 所以您正在比较类似 152213894705-12 15:00:00
  • 对我来说 date() 从 Unix 时间戳返回一个根据给定格式字符串格式化的字符串;因此它将返回03-26 11:49:33,如示例所示。我可能错了,但我不明白为什么我的 sn-p 工作
  • ...哦天哪-别理我,我的大脑显然已经睡着了,你是对的...我可能在想time()-我基本上只用过DateTime这么久我都忘记了其他功能是如何工作的:|
【解决方案2】:

你可以试试这样的

function convertMonthStringToInt($strMonth) {
   $month = array(
       'Jan' => 0,
       'Feb' => 1,
       'Mar' => 2,
       'Apr' => 3,
       'May' => 4,
       'Jun' => 5,
       'Jul' => 6,
       'Aug' => 7,
       'Sep' => 8,
       'Oct' => 9,
       'Nov' => 10,
       'Dec' => 11,
   );

   return $month[$strMonth];
}

function findYear($monthLog) {
   $currentYear = date('Y');
   $currentMonth = date('M');

   if(convertMonthStringToInt($monthLog) > convertMonthStringToInt($currentMonth)) {
      return $currentYear - 1;
   }
   else {
      return $currentYear;
   }
}

然后你可以使用 findYear 函数找到正确的年份

findYear('Nov'); // 2017
findYear('Jan'); // 2018
findYear('Mar'); //2018
findYear('Aug'); // 2017 

等等……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-19
    • 2019-11-24
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多