我有一个时间戳字符串,其中包含日期和时间,格式如下:
$time == "Apr 3, 2015 16:58:46.461897000";
我需要将它转换为PHP中的DateTime
对象,以便我可以对它执行进一步的操作。
因为此格式为not here in the list of supported formats。
所以问题是我怎样才能实现我的需要?
我的意思是给定的字符串包含格式的日期和时间,如月份 - 短名称日期,年份时间:分钟:秒。我需要将此字符串转换为 PHP DateTime object.
答案 0 :(得分:2)
如果您可以安全地删除纳秒,那么您可以使用随机字节 format code来计算额外的数字:
$input = 'Apr 3, 2015 16:58:46.461897000';
$output = DateTime::createFromFormat('M j, Y G:i:s.u???', $input);
var_dump($input, $output);
string(31) "Apr 3, 2015 16:58:46.461897000"
object(DateTime)#1 (3) {
["date"]=>
string(26) "2015-04-03 16:58:46.461897"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Madrid"
}
答案 1 :(得分:1)
试试这个;
<?php
$date=date_create_from_format("M j, Y H:i:s.u???","Apr 3, 2015 16:58:46.461897000");
echo date_format($date,"M j Y H i s u");
?>
答案 2 :(得分:1)
这是一个逐步的过程php脚本:
// Declare the string
$DateTime_String = "Apr 3, 2015 16:58:46.461897000";
// Convert the string into an array
$DateTime_Array = explode(' ', $DateTime_String);
// Create a new $Time_Array containing one element each for hours, minutes and seconds
$Time_Array = explode(':', $DateTime_Array[3]);
// Remove Hours:Minutes:Seconds element from $DateTime_Array
array_splice($DateTime_Array, 3, 1);
// Concatenate the two arrays
$DateTime_Array = array_merge($DateTime_Array, $Time_Array);
// Convert Simple Ordinal Array into Associative Array
$DateTime_Units = array('Month', 'Day', 'Year', 'Hour', 'Minute', 'Second');
$DateTime_Array = array_combine($DateTime_Units, $DateTime_Array);
// Lose the trailing comma on $DateTime_Array['Day']
$DateTime_Array['Day'] = str_replace(',', '', $DateTime_Array['Day']);
// Add a leading 0 to $DateTime_Array['Day'] (if necessary)
$DateTime_Array['Day'] = '0'.$DateTime_Array['Day'];
$DateTime_Array['Day'] = substr($DateTime_Array['Day'], -2, 2);
// Convert Month Shortname into two digit integer
$DateTime_Array['Month'] = date('m', strtotime($DateTime_Array['Month']));
// Build $New_DateTime_String
$New_DateTime_String;
$New_DateTime_String .= $DateTime_Array['Year'].'-';
$New_DateTime_String .= $DateTime_Array['Month'].'-';
$New_DateTime_String .= $DateTime_Array['Day'].' ';
$New_DateTime_String .= $DateTime_Array['Hour'].':';
$New_DateTime_String .= $DateTime_Array['Minute'].':';
$New_DateTime_String .= $DateTime_Array['Second'];
echo '<pre>';
echo '<p>'.$DateTime_String.'<p>';
print_r($DateTime_Array);
echo '<p>'.$New_DateTime_String.'<p>';
echo '</pre>';