Viewed   114 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

2

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, August 31, 2022
3

DateInterval is buggy on windows platform. See bug #51183. The official answer seems to be "use VC9 builds instead for now".

Monday, August 15, 2022
 
3

I use following wrapper class in my php5.2 apps: http://pastebin.ca/2051944. Untill php5.3 was released - it saves much my time

Thursday, November 3, 2022
 
2

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.

Thursday, September 1, 2022
 
4

if you have a date in a string with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:

DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy", 
                                  CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
Friday, August 5, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :