将时间戳转换为.ics iCal兼容日期格式

Cla*_*ire 1 php icalendar

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

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

当前我的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";
...

?>
Run Code Online (Sandbox Code Playgroud)

Roh*_*bhu 6

查看是否可行:

date('Ymd\THis', $time)
Run Code Online (Sandbox Code Playgroud)

$time可以是startDateendDate来自您的查询字符串。如果您不想要时间:

date('Ymd', $time)
Run Code Online (Sandbox Code Playgroud)

注意(感谢Nicola)在这里,$time必须是一个有效的UNIX时间戳,即它必须表示自该时期以来的秒数。如果它表示毫秒数,则需要先将其除以1000。

编辑正如lars k指出的那样,您需要添加\Z到两个字符串的末尾。

编辑正如Nicola指出的那样,您实际上并不需要它。


tim*_*ann 5

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

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

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

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

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

从格林威治标准时间开始 1 小时的班次会产生这样的结果

20150601T10:38+01:00
Run Code Online (Sandbox Code Playgroud)

在 PHP 中使用日期时,最好使用DateTime对象,这样您就可以轻松地使用和更改时区

// 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') ;
Run Code Online (Sandbox Code Playgroud)