Asked  7 Months ago    Answers:  5   Viewed   40 times

I have already researched a lot of site on how can I convert PHP DateTime object to String. I always see "String to DateTime" and not "DateTime to String"

PHP DateTime can be echoed, but what i want to process my DateTime with PHP string functions.

My question is how can I make PHP dateTime Object to a string starting from this kind of code:

$dts = new DateTime(); //this returns the current date time
echo strlen($dts);

 Answers

58

You can use the format method of the DateTime class:

$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');

If format fails for some reason, it will return FALSE. In some applications, it might make sense to handle the failing case:

if ($result) {
  echo $result;
} else { // format failed
  echo "Unknown Time";
}
Wednesday, March 31, 2021
 
cusejuice
answered 7 Months ago
72

Try this:

$tZone = new DateTimeZone("Europe/Amsterdam");
Saturday, May 29, 2021
 
mnagel
answered 5 Months ago
35

take a look at the date fortmats. if you use - as separator, php assumes it's y-mm-dd, but your order is dd-mm-y. the easiest way would be to change the separator to . wich would then be dd.mm.y.

Saturday, May 29, 2021
 
turik
answered 5 Months ago
41

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;
Friday, June 4, 2021
 
Jesse
answered 5 Months ago
80

Use DateTimeOffset.UtcDateTime:

DateTime utc = myDTO.UtcDateTime; // 01/15/2015 22:37:00
Wednesday, October 6, 2021
 
tika
answered 3 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :