解析可能没有零填充单位的可变长度日期时间字符串(“m/d/yyyy H:i:s”或“mm/dd/yyyy H:i:s”)

发布于 2024-08-20 11:48:50 字数 174 浏览 3 评论 0原文

如何转换格式如下的日期字符串:

m/d/yyyy H:i:smm/dd/yyyy H:i:s

和格式它就像:

yyyy-mm-dd H:i:s

我可以将两个输入中的任何一个格式化为我想要的格式,但不能同时格式化两者。

How would you convert a date string that might be formatted like:

m/d/yyyy H:i:s or mm/dd/yyyy H:i:s

and format it like:

yyyy-mm-dd H:i:s

I can format either of the two inputs into my desired format, but not both.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

疧_╮線 2024-08-27 11:48:50

strtotime() 解析这两种日期时间格式没有问题。

然后只需将其返回的 unix 时间戳整数与 date() 结合使用即可生成所需的格式字符串。

function format_date($date) {
    return date('Y-m-d H:i:s', strtotime($date));
}

strtotime() will have no problem parsing these two datetime formats.

Then just use its return unix timestamp integer with date() to generate the desired format string.

function format_date($date) {
    return date('Y-m-d H:i:s', strtotime($date));
}
凯凯我们等你回来 2024-08-27 11:48:50

最简单的方法是先使用 strtotime 将其转换为 unix 时间,然后再运行 strftime ...这不是最好的做法,但它消除了很多潜在的格式解析问题 :-)

Easiest way would be to simply transform it to unix time first with strtotime then run strftime on it afterwards... not the bes practice but it eliminates alot of the potential format parsing issues :-)

━╋う一瞬間旳綻放 2024-08-27 11:48:50

现在格式化的怎么样了?如果您确定这些是您可能作为输入的唯一两种日期格式,那么您可以在正斜杠上explode()它,然后如果strlen() 在月份或日期上返回 1,在创建 yyyy-mm-dd 字符串时添加 0。

但是,如果您不能保证这些是您唯一的两种输入格式,那么我会使用 strtotime() 将其转换为纪元,然后使用 date() 来将其格式化为您想要的格式。处理命中稍大,但代码更通用。

How are you formatting it now? If you're certain that those are the only two date formats you'll possibly have as input, then you can explode() it on the forward slashes, then if strlen() returns 1 on the month or the date, add a 0 as you're creating your yyyy-mm-dd string.

However, if you're not guaranteed that those are your only two input formats, then I would use strtotime() to convert it to epoch, then use date() to format it as you desire. A slightly bigger processing hit, but much more universal code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文