Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust a PHP date to the current year

Tags:

date

php

I have a PHP date in a database, for example 8th August 2011. I have this date in a strtotime() format so I can display it as I please.

I need to adjust this date to make it 8th August 2013 (current year). What is the best way of doing this? So far, I've been racking my brains but to no avail.

like image 919
Adam Moss Avatar asked Dec 21 '22 01:12

Adam Moss


2 Answers

Some of the answers you have so far have missed the point that you want to update any given date to the current year and have concentrated on turning 2011 into 2013, excluding the accepted answer. However, I feel that examples using the DateTime classes are always of use in these cases.

The accepted answer will result in a Notice:-

Notice: A non well formed numeric value encountered......

if your supplied date is the 29th February on a Leapyear, although it should still give the correct result.

Here is a generic function that will take any valid date and return the same date in the current year:-

/**
 * @param String $dateString
 * @return DateTime
 */
function updateDate($dateString){
    $suppliedDate = new \DateTime($dateString);
    $currentYear = (int)(new \DateTime())->format('Y');
    return (new \DateTime())->setDate($currentYear, (int)$suppliedDate->format('m'), (int)$suppliedDate->format('d'));
}

For example:-

var_dump(updateDate('8th August 2011'));

See it working here and see the PHP manual for more information on the DateTime classes.

You don't say how you want to use the updated date, but DateTime is flexible enough to allow you to do with it as you wish. I would draw your attention to the DateTime::format() method as being particularly useful.

like image 97
vascowhite Avatar answered Jan 06 '23 05:01

vascowhite


strtotime( date( 'd M ', $originaleDate ) . date( 'Y' ) );

This takes the day and month of the original time, adds the current year, and converts it to the new date. You can also add the amount of seconds you want to add to the original timestamp. For 2 years this would be 63 113 852 seconds.

like image 30
Frank Houweling Avatar answered Jan 06 '23 03:01

Frank Houweling