Carbon 将 Iso 8601 字符串解析为 UTC 日期并将其记录到 db [英] Carbon parse Iso 8601 string to UTC date and record it to db
问题描述
我有以下 Iso8601 日期时间字符串 2018-03-12T10:34:15-0200
并且在我解析它之后
I have the following Iso8601 date-time string 2018-03-12T10:34:15-0200
and after I parse it
Carbon::parse("2018-03-21T10:34:15-0200", 'UTC')
并将其保存到 mysql db datetime
列我有 2018-03-21 10:34:15
所以我丢失了 -0200代码>与UTC时区的小时差.
and save it to mysql db datetime
column I have 2018-03-21 10:34:15
so I've lost the -0200
hours difference with UTC timezone.
任何想法如何以正确的方式解决它?
Any ideas how to solve it the right way?
推荐答案
您不需要将时区作为解析函数的第二个参数传递.时区已经是日期字符串的一部分.如果您需要在 UTC 中保存日期,只需在解析后将其转换为 UTC 时区,如下所示:
You don't need to pass time zone as a second parameter to parse function. Time zone is already part of date string. If you need to save date in UTC just convert it to UTC timezone after parsing like so:
Carbon::parse("2018-03-21T10:34:15-0200")->setTimezone('UTC')
转换日期为:2018-03-21 12:34:15.0 UTC (+00:00)
Converted date will be: 2018-03-21 12:34:15.0 UTC (+00:00)
这篇关于Carbon 将 Iso 8601 字符串解析为 UTC 日期并将其记录到 db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!