Reputation: 349
I have a timestamp string which contains date and time in a format like this:
$time == "Apr 3, 2015 16:58:46.461897000";
I need to convert it to a DateTime
object in PHP, so that I can perform further operations on it.
Because this format is not here in the list of supported formats.
So the question is that how can I achieve what I need?
I mean the given string contains the date and time in format like Month-short-name Date, Year Hours:Minutes:seconds. I need this string to be converted to be PHP DateTime object.
Upvotes: 1
Views: 102
Reputation: 29453
Here is a step-by-step procedural php script:
// 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>';
Upvotes: 1
Reputation: 21386
Try this;
<?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");
?>
Upvotes: 1
Reputation: 146410
If you can safely drop the nanoseconds then you can use the random byte format code to account for the extra digits:
$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"
}
Upvotes: 2