TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

PHP Current Date, Yesterday Time based on DateTime();

Basically in my MySQL record database. There is a database field called "time" and that is set as Datetime.

$today = "";
$yesterday = "";
$currentmonth = "";
$lastmonth = "";

How do I get the following variables based on the Datetime(); the records appear with time like so (I was considering replacing the string after so many characters but speed is an issue?)

2011-11-10 11:59:45
2011-11-10 11:57:12
2011-11-10 11:55:29
2011-11-10 11:54:55
2011-11-10 11:54:21

Upvotes: 0

Views: 882

Answers (2)

Jigar Tank
Jigar Tank

Reputation: 1774

You can try this :

$time = strtotime("2011-11-10 11:59:45");
$day = date("d",$time);
$month = date("m",$time);
$year = date("Y",$time);

You can use date("d")+1 or date("d")-1 to get day after tomorrow or yesterdays date. Same is the case for month and year.

Upvotes: 1

Helen
Helen

Reputation: 811

You can use the php datetime functions to add or remove numbers of days/hours etc as required.

You can also then format the datetime to only display a month or day.

This formats it: http://www.php.net/manual/en/datetime.format.php

This modifies it: http://www.php.net/manual/en/datetime.add.php

This creates it: http://www.php.net/manual/en/datetime.createfromformat.php

So you could do something along the lines of:

$timeString = "2011-11-10 11:54:21";
$today= date_create_from_format('Y-m-d H:i:s', $timeString);
$yesterday = date_add($today, date_interval_create_from_date_string('-1 day'));
$currentMonth = date_format($today, 'm');
$lastMonthDate = date_add($today, date_interval_create_from_date_string('-1 month'));
$lastMonth= date_format($lastMonthDate , 'm');

Upvotes: 0

Related Questions