How do I convert the following type of timestamp to seconds since beginning of unix epoch in PHP

huangapple go评论89阅读模式
英文:

How do I convert the following type of timestamp to seconds since beginning of unix epoch in PHP

问题

我有以下字符串:

2023-05-10T22:32:21+02:00

我需要将其转换为自1970年1月1日00:00:00 GMT以来的秒数(Unix纪元)

我不关心+02:00部分。我只需要PHP代码将上述内容转换为秒数。我想我可以将T拆分成两个字符串,然后我将得到日期,然后右侧是时间,然后以某种方式解决这个问题,但不确定如何做到这一点。
英文:

I have the following string:

2023-05-10T22:32:21+02:00

I need to convert it to seconds since January 1 1970 00:00:00 GMT (Unix Epoch)

I do not care about the +02:00 section. I just need PHP code to convert the above to a number of seconds. I suppose, I can split the T into 2 strings and then I will have the date and then the time on the right side and then somehow work it out that way but not 100% sure on how to do this.

答案1

得分: 2

以下是翻译好的部分:

你的日期看起来是ISO 8601格式。

使用DateTime::createFromFormat创建一个DateTime对象。有了DateTime对象,你可以调用format方法,其中内置了一个用于表示自Unix纪元以来的秒数的'U'格式选项。

U 自Unix纪元(1970年1月1日00:00:00 GMT)以来的秒数

$dt = DateTime::createFromFormat(DateTimeInterface::ISO8601, '2023-05-10T22:32:21+02:00');

echo $dt->format('U');

结果:1683750741

你可以通过取得的时间戳值,并使用date()函数来从时间戳值创建日期并显示来验证这个工作。

$dt = DateTime::createFromFormat(DateTimeInterface::ISO8601, '2023-05-10T22:32:21+02:00');

$ts = $dt->format('U');

echo date(DATE_RFC2822, $ts);

结果:Wed, 10 May 2023 22:32:21 +0200

英文:

Your date looks to be in the ISO 8601 format.

Make a DateTime Object, with DateTime::createFromFormat. With the DateTime object, you can then call the format method that has a built in 'U' formating option for Seconds since unix epoch.

> U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

<?php

$dt = DateTime::createFromFormat(DateTimeInterface::ISO8601, '2023-05-10T22:32:21+02:00');

echo $dt->format('U');

Result: 1683750741

You can verify this worked by taking the timestamp value you got, and using the date() function to make a date from the timestamp value, and display it.

$dt = DateTime::createFromFormat(DateTimeInterface::ISO8601, '2023-05-10T22:32:21+02:00');

$ts = $dt->format('U');

echo date(DATE_RFC2822, $ts);

Result: Wed, 10 May 2023 22:32:21 +0200

huangapple
  • 本文由 发表于 2023年5月11日 07:03:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定