【问题标题】:How to change the format of the datetime along with changing from 12 hour to 24 hour?如何更改日期时间的格式以及从 12 小时更改为 24 小时?
【发布时间】:2017-07-14 18:00:27
【问题描述】:

如果我有这个日期:"16/2/2014 3:41:01 PM" 并想将其更改为格式:"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 datetime format


【解决方案1】:

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

http://php.net/manual/en/function.strtotime.php

http://php.net/manual/en/datetime.formats.php

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

但是,如果这不是一个选项,根据您提供的内容,一种方法是将162 从 DMY 格式转换为 MDY 格式。这是一个关于如何使用explode() 和字符串连接的示例:

<?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()的输出是string(19) "2014-02-16 15:41:01"

【讨论】:

  • 完美!谢谢:D
【解决方案2】:

使用此功能

日期和时间格式

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 = date_his();

它会考虑current datecurrent time

3:如果你想像这样存储来自日期字段调用的date

$date = date_his($_POST['field_name']);

奖金

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

【讨论】:

  • 我没有看到这如何解决原始问题?
猜你喜欢
  • 1970-01-01
  • 2021-08-05
  • 2018-10-26
  • 2012-11-11
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多