I want to convert this date-time string 2022-09-30T21:39:25.220185674Z to yyyy-mm-dd hh:mm:ss but it returns 1970-01-01 01:00:00 everytime.
Tried with: date('Y-m-d H:i:s', strtotime('2022-09-30T21:39:25.220185674Z')); or date('Y-m-d\TH:i:s', strtotime('2022-09-30T21:39:25.220185674Z'));
Can you help find out which format this is and how i could corretly format such string in PHP?
Went through this question or this one couldn't help.
It's a ISO 8601 datetime string with microseconds, where Z is the timezone "Zulu" or UTC + 0 hours.
ISO 8601 can be parsed with DateTime() like this:
$string = '2022-09-30T21:39:25.220185Z';
//create DateTime object
$date = date_create_from_format( "Y-m-d\TH:i:s.uP" , $string);
echo $date->format( 'Y-m-d H:i:s.u' );
However This will not work with your string, as the u parameter in the format "Y-m-d\TH:i:s.uP" which represents the microseconds, in PHP takes a maximum of 6 digits, and yours has 9.
You can resolve this by removing all above 6 digits from the microseconds part of the string with a regex, like
$string = '2022-09-30T21:39:25.220185674Z';
$new_string = preg_replace( '/^.*?\.\d{0,6}\K\d*/' , '' , $string );
$date = date_create_from_format( "Y-m-d\TH:i:s.uP" , $new_string );
echo $date->format('Y-m-d H:i:s.u');
Output: 2022-09-30 21:39:25.220180
The regex explained:
1. ^.*?\.\d{0,6} // select from the begin everything including the dot
// and max 6 digits
2. \K // forget the previous match and start again from the
// point where 1. ended
3. \d* // select all digits left
4. replace the match with ""
With '?' in the format, all digits after the 6th digit can be cut off.
$string = '2022-09-30T21:39:25.220185123Z';
$date = date_create_from_format( "Y-m-d\TH:i:s.u???P" , $string);
var_dump($date);
https://3v4l.org/Upm6v
As of PHP version 8.0.10, strings like '2022-09-30T21:39:25.220185674Z' are recognized by DateTime without any problems.
$str = '2022-09-30T21:39:25.220185674Z';
$d = new DateTime($str);
var_dump($d);
/*
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-30 21:39:25.220185"
["timezone_type"]=>
int(2)
["timezone"]=>
string(1) "Z"
}
*/
https://3v4l.org/pI4kO
Related
I am dealing with a problem of time conversion from 12 hr format to 24 hour format.
Is there any single function in php to replace the first two characters of a string?
str_replace can be used only when I know the substring content to be replaced.
$str_to_replace = '12';
$input_str = 'ab345678';
$output_str = $str_to_replace . substr($input_str, 2);
echo $output_str;
"12345678"
If the date is always given in a specific format you could try to convert it to a DateTime object and format the output.
$dateString = '15-Feb-2009 2:24 PM';
$date = DateTime::createFromFormat('j-M-Y g:i A', $dateString);
echo $date->format('Y-m-d G:i'); // will show "2009-02-15 14:24"
In general you should try in avoid holding a date in a string. Convert it to a DateTime -- this makes it also easier for you to manipulate the object (e.g. move date +1 day)
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.
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"
}
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");
?>
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>';
This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 6 years ago.
I have a String on the form: "dd/mm-yyyy", where dd is day of the month with two digits, mm is the month represented with two digits, and yyyy is the year with four digits.
I need to store this in my database. Ive tried
$dato = date('d/m-Y' ,strtotime($_POST['dag'] )
But that clearly doesnt work. In my database the date displays as yyyy-mm-dd. How do I properly convert the String to the correct format?
strtotime not accept your time string format, so it return false. You can use DateTime::createFromFormat or date_create_from_format, manual here.
DateTime::createFromFormat('d/m-Y', $_POST['dag']);
check the live demo
<?php
var_dump(DateTime::createFromFormat('d/m-Y', '11/01-2017'));
putput:
object(DateTime)#1 (3) {
["date"]=>
string(26) "2017-01-11 14:34:53.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
Try to replace the / with a - like so:
$date = "02/04-2016";
$dateNew = str_replace("/","-",$date);
You can use DateTime::createFromFormat:
$time = '12/3-1987';
$data = DateTime::createFromFormat('d/m-Y', $time);
echo $data->format('Y-m-d'); //1987-03-12
sandbox
I am having trouble with the following string which is supposed to be a datetime (response from an api).
2013-03-08T19:11:11.234+0000
I need to convert the string to ISO 8601.
The exact format should look like:
2016-03-01T12:00:00+00:00
If someone could help me do this in php would be great but I would be already more than happy if someone could identify the format (like yyyy-mm-ddThh:mm:ss).
It seems the API returns the time with milliseconds.
Try this:
$date = '2013-03-08T19:11:11.234+0000';
$format = 'Y-m-d\TH:i:s.uO';
$dt = DateTime::createFromFormat($format, $date);
echo $dt->format(DateTime::ISO8601);
Result:
2013-03-08T19:11:11+0000
EDIT
Based on comments on your answer, you need to convert such a time:
2016-03-01T11:01:51.126044 00:00
Since it's not possible to parse this format with DateTime, you need to make it readable first.
There are many ways to do this. What we need is to add a + before timezone, so that my code above work.
If you are sure the date you get from the API is always this format, and that there will always be only 1 space in the string, just replace the string with a space:
$date = '2016-03-01T11:01:51.126044 00:00';
str_replace(' ', '+', $date);
$format = 'Y-m-d\TH:i:s.uP';
$dt = DateTime::createFromFormat($format, $date);
echo $dt->format(DateTime::ISO8601);
This should work (note that here the timezone mask is P since there is a colon)
You can also use preg_replace() instead of DateTime, if you don't need the date for calculations:
$date = '2016-03-01T11:01:51.126044 00:00';
$date = preg_replace('`(\.[0-9]+\s)`', '+', $date);
echo $date;
This produces:
2016-03-01T11:01:51+00:00
If you need the date for calculation, just convert it to DateTime after:
$date = '2016-03-01T11:01:51.126044 00:00';
$date = preg_replace('`(\.[0-9]+\s)`', '+', $date);
$date = DateTime::createFromFormat(DateTime::ISO8601, $date);
var_dump($date);
This produces:
object(DateTime)#1 (3) {
["date"]=>
string(26) "2016-03-01 11:01:51.000000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+00:00"
}
I suggest you to use Carbon: http://carbon.nesbot.com/docs/
echo Carbon::parse('2013-03-08T19:11:11.234+0000')->toAtomString();
Also, the format you want is ATOM, not ISO 8601. You could do #Arcesilas way, it should work too.
I have problem with date function in php. If I supply string in format "d.m.y" for example "01.01.01" it gets rendered as todays date which means that php gets confused.
I found:
Note:
The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy)
only works for the year values 61 (inclusive) to 99
(inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has
precedence.
on: php.net site
How to override this behavior?
I know of date_create_from_format function which would work fine if I knew input will always be in format "d.m.y", but it won't.
UPDATE 1:
Code
$date = new DateTime('01.01.01');
echo $date->format('Y-m-d');
outputs 2010-10-19 and I wanted 2001-01-01.
To format a date other than now, use the second parameter. For example:
echo date("d.m.y", 1255982665);
echoes 19.10.09
Just read the documentation! PHP's site is excellent
It seems like you want to reformat a date?
mktime() gives unix timestamp from component pieces
date() gives string from unixtimestamp (or implied now)
getdate() gives assoc array from unix timestamp
I think you want -
$arr = explode($dateIn, ':'); //get array [day, month, year]
$timestamp = mktime(0,0,0, $arr[0], $arr[1], $arr[2]) //unix time stamp, a long integer representing time
date(DESIREDFORMAT, $timestamp);
check out the output formats here - http://us2.php.net/manual/en/function.date.php
function getDateFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date->getTimestamp();
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return strtotime( $str );
}
echo date( 'd.m.Y H:i', getDateFromString( '01.01.01' ) ); // 01.01.2001 20:14
Edit
To adjust it a bit more to get your exact output:
function getDateTimeFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date;
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return new DateTime( $str );
}
$date = getDateTimeFromString( '01.01.01' );
echo $date->format( 'Y-m-d' ); // 2001-01-01