1

I can think of a very long winded way to do the following by exploding the string and then setting up variables which convert each numerical month into a textual month but before I do all of that is there a simpler way to do the following?

I have a date stored in a variable like this :

$date = '21/05/16';

I need to convert it into a Unix Timestamp using the date, month and year from the variable with the current timestamp for the hours, mins & seconds.

The way I described above would end up using strtotime like this :

$unixtimestamp = strtotime("21 May 2016");

But like I said, I'd have to explode the $date variable by '/' then convert each numerical month to a textual one (05 = May etc) and finally inject the '20' to the front of each year. This just seems really long winded, is there a better way?

Lastly, I'm not sure how I would add the current hours,mins,secs to the strtotime() even if I did have to do it the way I described above so any pointers on that would be great please.

Any help greatly appreciated.

Grant
  • 1,297
  • 2
  • 16
  • 39

1 Answers1

2

You can use the DateTime object :

$date = '21/05/16';
$dateObject = DateTime::createFromFormat('d/m/Y', $date);
$timestamp = $date->getTimestamp();

And you are done :)

EDIT : to go further, you can manipulate your date and add hours or so :

$dateObject->add(new DateInterval('P4H3M2S')); 

It adds 4 hours, 3 minutes and 2 seconds the the date. Beware, it doesn't return a new date, it modifies the date object you are manipulating.

JesusTheHun
  • 1,217
  • 1
  • 10
  • 19