Php 如何将datetime的格式从12小时更改为24小时?

Php 如何将datetime的格式从12小时更改为24小时?,php,datetime,format,Php,Datetime,Format,如果我有此日期:2014年2月16日下午3:41:01,并希望将其更改为格式:2014-02-16 15:41:01。 我如何使用PHP实现它? 我试过这个: $date = "16/2/2014 3:41:01 PM" $newDate = date("Y-m-d H:i:s", strtotime($date)); 但是它一直返回1970-01-01 00:00:00。就PHP读取和解析日期的方式而言,$date字符串的当前格式无效-请参阅以下两个URL以了解详细信息: 基本上,当使用斜杠

如果我有此日期:2014年2月16日下午3:41:01,并希望将其更改为格式:2014-02-16 15:41:01。 我如何使用PHP实现它? 我试过这个:

$date = "16/2/2014 3:41:01 PM"
$newDate = date("Y-m-d H:i:s", strtotime($date));

但是它一直返回1970-01-01 00:00:00。

就PHP读取和解析日期的方式而言,$date字符串的当前格式无效-请参阅以下两个URL以了解详细信息:

基本上,当使用斜杠/作为日期分隔符时,PHP假定您输入的是MM/DD/YYYY。如果可能的话,我会考虑更新创建该日期字符串的任何输入,将其保存为MM/DD/YYYY格式——这可能是最好的解决方案

然而,如果这不是一个选项,根据您给出的,一种方法是将16和2从DMY格式转换为MDY格式。下面是一个关于如何使用分解和字符串连接来完成此操作的示例:

<?php

// The original string you provided, with a date in `DD/MM/YYYY` format
$dateString = "16/2/2014 3:41:01 PM";

// The explode function will let us break the string into 3 parts, separated by the forward slashes. Using your example, these gives us an array containing the following:
// 0 => '16'
// 1 => '2'
// 2 => '2014 3:41:01 PM'
$stringPieces = explode('/', $dateString, 3);

// Piece the above array back together, switching the places of entries 0 and 1 to create a date in the format `MM/DD/YYYY`. This results in:
// 2/16/2014 3:41:01 PM"
$newDateString = $stringPieces[1] . '/' . $stringPieces[0] . '/' . $stringPieces[2];

// Use the reformatted date string in the date() function:
$newDate =  date("Y-m-d H:i:s", strtotime($newDateString));

var_dump($newDate);
在我的测试中,var_dump的输出是string19 2014-02-16 15:41:01

使用此函数

日期和时间格式 1:这个功能对你有帮助

function date_his($date = '')
{
    if ($date == '') {
        return $date = date("Y-m-d H:i:s");
    } else {
        $date = date("Y-m-d H:i:s", strtotime($date));
    }
    return $date;
}
2:在存储到数据库时,像这样调用此函数

$date=日期

将考虑当前日期和当前时间

3:如果您想存储date from date字段,请这样调用

$date=date\u his$\u POST['field\u name']

奖金
它将任何日期和时间格式转换为YYYY-mm-dd HH:mm:ss

完美!谢谢:我看不出这是如何解决最初的问题的?设置默认时区以获得准确的结果。