$data['user']['time'] = '2011-03-07 00:33:45';
how can we add 1 year to this date ?
something like $newdata = $data['user']['time'] + 1 year
?
or
$newdata = 2012-03-07 00:33:45
Thanks
Adam Ramadhan
we will help you to give example of php add 1 year to current date. $date = "2022-02-01"; $newDate = date('Y-m-d', strtotime($date.
If you don't want to use the DateTime class then you can simply use the PHP's date() function to get the year from date.
For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".
Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. echo "$date1 is older than $date2" ; ?>
strtotime()
is the function you're looking for:
$data['user']['seal_data'] = date('Y-m-d H:i:s', strtotime('+1 year', strtotime($data['user']['time'])));
First, you have to convert the MySQL datetime
to something that PHP can understand. There are two ways of doing this...
Use UNIX_TIMESTAMP()
in your query to tell MySQL to return a UNIX timestamp of the datetime
column.
SELECT whatever, UNIX_TIMESTAMP(myTime) AS 'myUnixTime' FROM myTable;
Use DateTime::createFromFormat
to convert your string time to something PHP can understand.
$date = DateTime::createFromFormat('Y-m-d H:i:s', $data['user']['time']);
Once that is done, you can work with the time... Depending on the method you used above, you can use one of the following.
If you have a unix timestamp, you can use the following to add a year:
$inAYear = strtotime('+1 year', $data['user']['unixTime']);
If you have a DateTime
object, you can use the following:
$inAYear = $date->add(new DateInterval('P1Y'));
Now, to display your date in a format that is respectable, you must tell PHP to return a string in the proper format.
If you have a unix timestamp, you can use the following:
$strTime = date('Y-m-d H:i:s', $inAYear);
If you have a DateTime
object, you can use the following:
$strTime = $inAYear->format('Y-m-d H:i:s');
Alternatively, if you don't want to deal with all of that, you can simply add one year when you query.
SELECT whatever, DATE_ADD(myTime, INTERVAL 1 YEAR) AS 'inAYear' FROM myTable;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With