【问题标题】:Getting timestamp from relative date/time string with specific timezone AND specific $now value从具有特定时区和特定 $now 值的相对日期/时间字符串中获取时间戳
【发布时间】:2013-01-08 16:58:57
【问题描述】:

我知道有两种方法可以从 PHP 中的相对日期/时间字符串中获取时间戳:

strtotime:允许用户指定自己的 $now 值

DateTime 对象:允许用户指定自己的 $timezone 值

有没有一种方法可以从日期/时间字符串中获取时间戳,允许同时指定时区和 $now 值?似乎唯一的方法是使用 strtotime 同时临时覆盖整个 php 应用程序的默认时区,然后立即将其设置回来。这似乎是一个 hacky 解决方案,如果有更清洁的方法就好了。

编辑:似乎对我正在尝试做的事情有些误解。这是一个更具体的例子:

“我想在 America/Los_Angeles 时区内查找与字符串 'next tuesday at 3:00pm' 对应的时间戳,并为 $now 指定任意值,例如 2014 年 3 月 14 日上午 8:05。”

【问题讨论】:

标签: php datetime timezone strtotime


【解决方案1】:

我准备了一个例子。这可能是你想要的:

<?php

// Including the timezone int the time strings (thanks @Mike B!!!) 
// will make it very easy.  just strtotime() is required

// create a timestamp for March 14th PDT
$now = strtotime('14 March 2014 8:05am America/Los_Angeles');

// get the requested timestamp.
$nexTuesday = strtotime('next tuesday 3:00 pm America/Los_Angeles', $now);

【讨论】:

  • 谢谢,但这不是我想要的。例如,您如何计算“下周二下午 3 点在柏林,假设当前时间是 2014 年 3 月 14 日上午 9 点?”
  • 我看到你编辑了它......它更接近我的需要,但它仍然缺少“为 $now 指定任意值,例如 2014 年 3 月 14 日上午 8:05”部分
  • 如此接近!一秒钟我认为它可能真的有效,但问题是 strtotime 将使用默认时区,并且“下周二 3:00 pm”将意味着不同的时间戳,具体取决于您的默认时区是什么,无论当前 UTC 是什么时间戳是。我希望能够明确设置该时区。
  • 我会说没关系。但在闰小时(阳光节约时间)的情况下,它确实很重要。让我再想一想:)
  • 你怎么能说没关系呢?纽约的“下周二下午 3:00”与东京的“下周二下午 3:00”相差 14 小时!我想说这是一个非常重要的区别。
猜你喜欢
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 2016-12-30
  • 2016-08-23
  • 1970-01-01
相关资源
最近更新 更多