Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date, hour and minute as separate variables from a datetimestamp in PHP

Tags:

php

In PHP if I have a variable ($getTimeStamp) that follows the format 0000-00-00 00:00:00 (i.e. 2013-09-26 13:06:00).

What is the easiest way to get the date ($getDate), hour ($getHour) and minute ($getMinute) as separate variables?

like image 520
fakeguybrushthreepwood Avatar asked Sep 26 '13 10:09

fakeguybrushthreepwood


People also ask

How can I get minutes between two dates in PHP?

$min = $interval ->days * 24 * 60; $min += $interval ->h * 60; $min += $interval ->i; // Printing the Result in Minutes format.

How can I get only hours from time in PHP?

By hours I'm assuming you mean if the time is 8PM or 20:00 hours like it is in your time string then... $date = "2011-07-26 20:05:00"; $date = strtotime($date); echo date('H', $date);

Can you compare time in PHP?

In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument. The diff() method will return a new object of type DateInterval .


2 Answers

The easiest way is to use PHP DateTime class

$getTimeStamp = '2013-09-26 13:06:00';
$date = new \DateTime($getTimeStamp);

$dateString = $date->format('Y-m-d');
$hourString = $date->format('H');
$minuteString = $date->format('i');
like image 180
Laurynas Mališauskas Avatar answered Sep 22 '22 14:09

Laurynas Mališauskas


It's not timestamp ;) Check what time() function returns, that's how timestamp looks like.

You can use something like that:

$time = strtotime($getTimeStamp);
$getDate = date('Y-m-d', $time);
$getHour = date('H', $time);
$getMinute = date('i', $time);
like image 38
Elon Than Avatar answered Sep 20 '22 14:09

Elon Than