0

Is this the correct way to get the current time in PHP using DateTime?

$currenttime = new DateTime(); $currenttime2 = $currenttime->format('H:i:s'); 
3
  • 3
    Um, did you try it? Did it look correct? Commented Aug 7, 2013 at 19:08
  • 1
    You'll probably want to prefix it with date_default_timezone_set("America/New York"); or whatever your timezone is. Other than that it should be fine. php.net/manual/en/function.date-default-timezone-set.php Commented Aug 7, 2013 at 19:20
  • yes its correct way, new DateTime(); Commented Aug 7, 2013 at 19:22

2 Answers 2

1

I believe you can do it like this

$date = date('Y-m-d H:i:s'); 
Sign up to request clarification or add additional context in comments.

2 Comments

but thats not DateTime right? because i need to compare it with another DateTime() object...
If you want to compare, then you must use $currenttime, don't recreate $currenttime2 as that is a string, not an object. $currenttime = new DateTime(); creates a DateTime object with the current time as default.
0

This will set the time based on your date time settings in php.ini. Do a var_dump of $currenttime after creation to see what I mean. You may also use microtime(true); to obtain a unix timestamp, which can be converted using other functions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.