Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current date/time as a date object in PHP

Tags:

How do you get today's date, as a date object?

I'm trying to compute the difference between some start date and today. The following will not work, because getdate() returns an array and not a date object:

$today = getdate();            $start = date_create('06/20/2012'); $diff = date_diff($start, $today);  echo($today . '<br/>' . $start . '<br/>' . $diff); 

Output:

Array ( [seconds] => 8 [minutes] => 1 [hours] => 16 [mday] => 11 [wday] => 1 [mon] => 6 [year] => 2012 [yday] => 162 [weekday] => Monday [month] => June [0] => 1339455668 )

DateTime Object ( [date] => 2012-06-20 00:00:00 [timezone_type] => 3 [timezone] => America/Los_Angeles )

like image 278
McGarnagle Avatar asked Jun 11 '12 23:06

McGarnagle


People also ask

How can I get current date and time in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.

How can I get current date in dd mm yyyy format in PHP?

$today = date('d-m-y'); to $today = date('dd-mm-yyyy');

How can I insert current date and time in database using PHP?

php $query = "INSERT INTO guestbook SET date = CURRENT_TIMESTAMP"; $sql = mysql_query($query) or die(mysql_error()); ?> Which means that it is automatically populated with the current date, the minute a record is created or updated.

How get fetch time from database in PHP?

PHP time() Functionecho(date("Y-m-d",$t));


1 Answers

new DateTime('now'); 

http://www.php.net/manual/en/datetime.construct.php

Comparing is easy:

$today = new DateTime('now'); $newYear = new DateTime('2012-01-01');  if ($today > $newYear) {  } 

Op's edit I just needed to call date_default_timezone_set, and then this code worked for me.

like image 129
Mike B Avatar answered Sep 18 '22 11:09

Mike B