nerdexam
Zend

200-710 · Question #60

QUESTION 63 Which of the following will NOT instantiate a DateTime object with the current timestamp?

The correct answer is D. $date = new DateTime(time()). Option D fails because PHP's DateTime constructor expects a string argument, and while PHP will coerce time()'s integer return value into a numeric string like "1723800000", the constructor has no way to interpret a bare numeric string as a Unix timestamp - it requires the @…

Date and Time

Question

QUESTION 63 Which of the following will NOT instantiate a DateTime object with the current timestamp?

Options

  • A$date = new DateTime();
  • B$date = new DateTime('@' . time());
  • C$date = new DateTime('now');
  • D$date = new DateTime(time());

How the community answered

(30 responses)
  • A
    10% (3)
  • B
    17% (5)
  • C
    3% (1)
  • D
    70% (21)

Explanation

Option D fails because PHP's DateTime constructor expects a string argument, and while PHP will coerce time()'s integer return value into a numeric string like "1723800000", the constructor has no way to interpret a bare numeric string as a Unix timestamp - it requires the @ prefix to signal that interpretation. This will either throw a warning/error or produce unexpected results.

Options A and C are both valid: passing no argument or the string 'now' both tell DateTime to use the current moment, as 'now' is an explicitly recognized relative time string. Option B works correctly because the @ prefix is the PHP convention for passing a Unix timestamp directly to DateTime - so '@' . time() produces a valid string like '@1723800000' that the constructor understands.

Memory tip: Think of @ as the "at this Unix timestamp" marker - without it, DateTime doesn't know whether a raw number is a year, a relative offset, or a timestamp, so it rejects it. @time() = valid; time() alone = invalid.

Topics

#DateTime#timestamp#time()#constructor

Community Discussion

No community discussion yet for this question.

Full 200-710 Practice