使用时区调整将源文本转换为时间


Converting source text to time with timezone adjustment

我有一个原始文本/xml信息文件,其中列出了当天发生的事件。每个事件的开始时间以24小时制00:00:00表示,以欧洲/伦敦时区为基础。我要做的是转换文件中找到的每个事件开始时间,使其以'g: I A'格式表示,并基于America/New_York时区。

如果我将源字符串定义为单个实例,下面的代码工作得很好:
//output will be 3:45 PM
$src_tm = '19:45:00';
$src_tz =  new DateTimeZone('Europe/London');
$dest_tz = new DateTimeZone('America/New_York');
$tm = new DateTime($src_tm, $src_tz);
$tm->setTimeZone($dest_tz);
$dest_tm = $tm->format('g:i A');
echo $dest_dt;

但是,正如我上面所说的,我想对文件中的每个实例都这样做。我已经提出了以下正则表达式来识别每个实例:'/'d+:'d+:00/',但我有极端困难使事情工作使用preg_replace和DateTime的正则表达式。我需要做些什么来确保文件中的每个开始时间都被识别并转换为'g: I A'和America/New_York?

我建议不要使用正则表达式来操作XML文件。这可能容易出错。

相反,可以使用类似SimpleXML的东西将XML文件解析为对象图,您可以安全地查询和操作其节点。在更新了每个相关节点中的日期格式和时区之后,可以将对象图保存为XML字符串。

Matt是正确的UTC而不是欧洲/伦敦。谢谢你指出来。是的,在我的例子中,没有必要指定一个特定的日期,因为我使用的信息每天都会更新。所以我所需要的就是默认的当前日期。

这样说,我能够在阅读了preg_replace_callback之后得到正确的东西。真管用!

//adjust event start time for America/New York 
$input = preg_replace_callback('/''d{2}:''d{2}:''d{2}/', 'replace_timestamp', $info);
function replace_timestamp($matches)
{
    $source_tz = new DateTimeZone('UTC');
    $destination_tz = new DateTimeZone('America/New_York');
    $time = new Datetime($matches[0], $source_tz);
    $time->setTimeZone($destination_tz);
    return $time->format('g:i A');
}