【问题标题】:Set file date modification via touch function通过触摸功能设置文件日期修改
【发布时间】:2017-06-29 01:23:02
【问题描述】:

我已经阅读http://php.net/manual/en/function.touch.php 了解如何设置文件修改日期,但我的日期格式是:

$date = "5/11/2017 08:32 PM EST";

如何触摸带有该日期的文件?

$filename = "text.txt";

if (!touch($filename, $date)) {
    echo 'Whoops, something went wrong...';
} else {
    echo 'Touched file with success';
}

【问题讨论】:

  • strtotime 可以将日期字符串转换为 Unix 时间戳
  • touch() 需要第二个参数是 UNIX 时间戳。 secure.php.net/manual/en/function.strtotime.php 这是一种方法,但我建议您使用 DateTime 方法以确保获得最佳结果
  • 顺便说一句;您还有其他关于解决方案的问题;最好将它们标记为已解决。它们被认为仍未解决/未解决。

标签: php date time


【解决方案1】:

使用strtotime() 将其转换为正确的格式:

$filename = "text.txt";

if (!touch($filename, strtotime($date))) {
echo 'Whoops, something went wrong...';
} else {
echo 'Touched file with success';
}

如果您对格式有 100% 的把握,请使用 DateTime::createFromFormat() 以确保 100% 的准确性(无论区域设置或区域如何):

$datetime = DateTime::createFromFormat("n/d/Y h:i A T", $date);

if (!touch($filename, $datetime->getTimestamp())) {
echo 'Whoops, something went wrong...';
} else {
echo 'Touched file with success';
}

您可以看到here 使用strtotime()DateTime::createFromFormat() 的结果相同。

【讨论】:

  • 最好检查 OP 以前的问题 ;-) 我给了他们一个slight friendly nudge
  • @Fred-ii- 检查 OP 以前的问题我能得到什么?我应该做些不同的事情吗?
  • 嗯,很多时候,人们发布许多问题并获得许多解决方案,但不要将它们标记为已解决。他们发布,他们得到他们的解决方案并逃跑。不知道你是否会在这里看到一个绿色的勾号,但我可能是错的。
  • 弗雷德,真实故事 :)
  • @Fred-ii- 所以你是说我应该避免回答不接受答案的发帖者的问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多