php - 使用 DateTime::CreateFromFormat 创建日期对象

标签 php datetime

我有一串日期:

25/08/2012

我在这里尝试将其转换为 DateTime 对象,以便将其保存到 MySQL 数据库中。我的后端架构有一个准备接收此数据的 DateOfPrint 日期 列。

这是我尝试过的:

$eventDate = DateTime::createFromFormat('d/m/y', $fecha->innertext);
echo $eventDate;

echo 语句在屏幕上没有显示任何内容,并且在尝试将其保存到数据库时,该列中没有保存任何内容。

有什么建议吗?

最佳答案

您的 $eventDate 包含一个打印为空字符串的 bool 值 (false)。

您需要使用大写的 Y。

Y   A full numeric representation of a year, 4 digits    Examples: 1999 or 2003
y   A two digit representation of a year    Examples: 99 or 03

你必须调用DateTime::format() ;
例如

<?php
$fecha = new StdClass;
$fecha->innertext = '25/08/2012';

$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
if ( false===$eventDate ) {
  die('invalid date format');
}
echo $eventDate->format('Y-m-d');

打印

2012-08-25

关于php - 使用 DateTime::CreateFromFormat 创建日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12074359/

相关文章:

php 用户注册 num 行不起作用

php - Laravel - withCount 返回错误,提示 SQLSTATE[42S22] : Column not found: 1247 Reference 'cars_count' not supported (forward reference in item list)

ruby - Rails 获取没有日期的当前时间

c# - 在 asp.net 中将数据表日期转换为 dd/mm/yyyy 格式

php - jQuery 通过 Ajax 调用 PHP 文件危险吗?

php - 加密密码列表

sql-server-2005 - SQL左联接(多个联接条件)

c# - LINQ to Entities 不支持“TimeOfDay” - 在 Linq 2 SQL 中查找总秒数

javascript - 如何将 JS Date 格式化为 C# 兼容的 DateTime?

php - 在数据库中记录成员生日的正确方法是什么?