简体   繁体   English

如何将字符串转换为日期

[英]How to convert string to date

I would convert a string like that "July 22, 2011 in 7:42pm" in a different format.我会以不同的格式转换像“2011 年 7 月 22 日晚上 7:42”这样的字符串。 I tried to use both strtotime and date_parse_from_format functions but they don't correctly work in this case.我尝试同时使用 strtotime 和 date_parse_from_format 函数,但在这种情况下它们不能正常工作。 I suppose that the reason of this problem could be the substring "in".我想这个问题的原因可能是 substring “in”。

How can I convert that format in a Date type or in a timestamp?如何将该格式转换为日期类型或时间戳?

I suppose that the reason of this problem could be the substring "in".我想这个问题的原因可能是 substring “in”。

As far as I can see you are right.据我所知,你是对的。 At least the i is an identifier ("Minutes with leading zeros") itself, thus you must escape it.至少i本身就是一个标识符(“带前导零的分钟”),因此您必须对其进行转义。

var_dump(date_parse_from_format('F d, Y \i\n g:ia', $string));

See date() Example #2请参阅date()示例 #2

Hey try the following solutions嘿尝试以下解决方案

print $date = "July 22, 2011 in 7:42pm";
$date = date_parse_from_format('F j, Y * h:iA', $date);
print '<pre>'; print_r($date);

I would convert a string like that "July 22, 2011 in 7:42pm" in a different format.我会以不同的格式转换像“2011 年 7 月 22 日晚上 7:42”这样的字符串。

The static method DateTime::createFromFormat() ( documentation ) (or alias date_create_from_format() ) is preferred.首选 static 方法DateTime::createFromFormat()文档)(或别名date_create_from_format() )。 Below is an example of its use for your needs, but be sure to absorb the information found in the documentation.下面是一个用于满足您需求的示例,但请务必吸收文档中的信息。

How can I convert that format in a Date type or in a timestamp?如何将该格式转换为日期类型或时间戳?

Below is a basic example.下面是一个基本的例子。 For the available formatting characters, see the date() manual page .有关可用的格式字符,请参阅date()手册页

$subject = 'July 22, 2011 in 7:42pm';
$datetime = DateTime::createFromFormat('F d, Y \i\n g:ia', $subject);

// Output as another format (2011-07-22 19:42:00)
echo $datetime->format('Y-m-d H:i:s');

// Output as Unix timestamp (1311327720)
echo $datetime->getTimestamp();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM