【问题标题】:Convert a timestamp to an .ics iCal compatible date format将时间戳转换为 .ics iCal 兼容的日期格式
【发布时间】:2023-03-15 05:42:01
【问题描述】:

我有一个日期,我通过 jQuery 中的 formatDate 函数将其存储为时间戳。然后,我将检索此值以制作一个 ics 文件,一个将事件时间和详细信息添加到用户日历的日历文件。但是时间戳格式在 ics 文件中不起作用,没有添加正确的日期,因此我需要将其转换为类似于 20091109T101015Z 的值。它是当前格式,因为时间戳看起来像 1344466800000这是来自 this example,这是我创建 ics 文件所遵循的。

我的 php 文件链接是 http:// 域。 com/icsCreator.php?startDate=1344380400000&endDate=1345503600000&event=Space%20Weather%20Workshop&location=London

当前我的 ics 文件看起来像

<?php
$dtStart=$_GET['startDate'];
$dtEnd=$_GET['endDate'];
$eventName=$_GET['event'];
$location=$_GET['location'];

...
echo "CREATED:20091109T101015Z\n";
echo "DESCRIPTION:$eventName\n";
echo "DTEND:$dtEnd\n";    
echo "DTSTART:".$dtStart."\n";
echo "LAST-MODIFIED:20091109T101015Z\n";
echo "LOCATION:$location\n";
...

?>

【问题讨论】:

  • 你能删除所有不属于日期问题的行吗?

标签: php icalendar


【解决方案1】:

看看这是否有效:

date('Ymd\THis', $time)

这里的$time 可能是您查询字符串中的startDateendDate。如果你不想要时间:

date('Ymd', $time)

注意(感谢 Nicola)这里,$time 必须是有效的 UNIX 时间戳,即它必须表示自纪元以来的秒数。如果代表毫秒数,需要先除以1000。

EDIT正如lars k所指出的,您需要在两个字符串的末尾添加\Z

EDIT 正如 Nicola 所指出的,您并不真正需要它。

【讨论】:

  • 谢谢,它现在设置了一个以前没有的日期,但它是错误的,我的开始时间是 71 年 6 月 10 日,结束时间是 2007 年 10 月 5 日!
  • 您可能希望将您的时间戳除以 1000。它以毫秒为单位吗?
  • @RohanPrabhu 成功了!我将我的变量更改为 $dtStart=date('Ymd',$_GET['startDate']/1000); $dtEnd=date('Ymd',$_GET['endDate']/1000);现在效果很好
  • @Nicola:我在你给我的例子中看到了这一点。如果没有它也能工作.. 太好了...
  • 您是否只想编辑您的答案以显示它需要除以 1000 并且我将其标记为正确?
【解决方案2】:

\Z 告诉系统时区。 Z 是祖鲁语或世界时。

如果您忽略它 - 那么您假设最终用户日历应用程序上的时区设置与您的系统生成时间戳的设置相匹配。

仅在美国就有多个时区 - 因此您不能仅根据您的用户与您在同一个国家/地区做出该假设。

为了使日期正确进入日历,您需要指定时区与 UTC 的偏移量为正负小时和分钟

注意: 日期('Ymd\THisP'); // P 是相对于 GMT 的偏移量,适用于所有日历用途。

如果从 GMT 偏移 1 小时,就会出现这样的情况

20150601T10:38+01:00

在 PHP 中使用日期时,最好使用 DateTime 对象,然后您可以轻松使用和更改 timezones

// Start with your local timezone e.g
$timezone = new \DateTimeZone('Europe/Amsterdam') ; 

// Don't be tempted to use a timezone abbreviation like EST
// That could mean Eastern Standard Time for USA or Australia.
// Use a full timezone: http://php.net/manual/en/timezones.php

$eventdate = new DateTime ( '1st September 2015 10:30', $timezone);

// Convert the time to Universal Time
$eventdate->setTimezone( new DateTimeZone('UTC') ) ; // Universal / Zulu time

// Return Event Date/Time in calendar ICS friendly format 
// comfortable in the knowledge that it is really in UTC time
return $eventdate->format('Ymd\THis\Z') ;

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 2015-10-26
    • 2019-02-25
    • 1970-01-01
    • 2015-08-19
    • 2020-02-23
    • 1970-01-01
    • 2011-03-05
    相关资源
    最近更新 更多