doz87
doz87

Reputation: 601

PHP new DateTime vs date()

I'm trying to write a basic log file for a script I am running and I want to insert the current date/time at the beginning of the log before the actual logging.

My code is the following:

$con = connectToDatabase();
$now = new DateTime;
$filePath = 'wipe-log.log';
$file = fopen($filePath, 'a+');

$log = "\n\n" . $now->date . " ----------------- \n\n\n";

fwrite($file, $log);

The only part of this that doesn't work is the date and I get an output of:

(newline)
(newline)
(missing date)      -----------------

But, if I switch to using the date() function like so:

$log = "\n\n" . date("F d Y H:i:s") . " ----------------- \n\n\n";

It works perfectly.

The other thing is that if I set some breakpoints in the code and step through this section of the code, it works perfectly. Makes me think that it isn't waiting for the instantiation of the DateTime object and so has nothing to print out.

I've had this issue with other things too and have just opted to find different ways around it but this is really bugging me now.

Upvotes: 1

Views: 5360

Answers (1)

gmsantos
gmsantos

Reputation: 1419

You need to use the format method to print the date from a DateTime object.

$con = connectToDatabase();
$now = new DateTime;
$filePath = 'wipe-log.log';
$file = fopen($filePath, 'a+');

$log = "\n\n" . $now->format("F d Y H:i:s"). " ----------------- \n\n\n";

fwrite($file, $log);

The time and date formats are the same you use in date functions.

Upvotes: 8

Related Questions