簡體   English   中英

在PHP中將字符串轉換為時間

[英]Converting string to time in PHP

我在嘗試將字符串轉換為時間時遇到了一些麻煩。

我的代碼是:

$time = strtotime("14 November, 2013 2:30 AM");
echo $time ."<br />";
echo date("m/d/Y", $time);

我知道strtotime並不是魔術,因此我簽出了可接受的日期/時間格式,但是我不確定如何將字符串轉換為另一個字符串而不先轉換為時間。

最簡單的方法是什么?

看一下DateTime :: createFromFormat,然后在創建的DateTime實例上調用format。

就像是:

$yourTimeString = '14 November, 2013 2:30 AM';
$date = DateTime::createFromFormat('d F, Y h:i A', $yourTimeString);
echo $date->format('m/d/Y');

一種方法是使用explodelist重寫字符串。

<?php
// here we assume "day month, year time AMPM"
$date = "14 November, 2013 2:30 AM";

// assign a variable to each part of the string
list($day,$month,$year,$time,$ampm) = explode(" ",$date);

// remove the commas at the end of the month
$month = str_replace(',','',$month);

// Now we rewrite the strtotime string
$time = strtotime($month . " " . $day . ", " . $year . " " . $time . " " . $ampm);

echo $time ."<br />";
echo date("m/d/Y", $time);

PHP date()函數允許使用自然語言字符串來解析日期,

for Ex:

echo date("d-M-Y", strtotime("first monday of 2019-07")); // returns first monday of july 2019

echo date("d-M-Y", strtotime("last sat of July 2008"));

您可以在此處找到將日期解析為自然語言的php指令。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM