Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time from a date/time string

Tags:

php

datetime

I have a date value stored in a variable. I need to extract the time part of the value in to a separate variable and then add/subtract time from it.

The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00

From the value 20110805124000 (which is stored in the variable $fulltime), I need to store the time only in the format 12:40 (so ignoring the year, month, day and seconds and adding the colon between the hour and minute) in a variable called $shorttime. I then need to add a number of hours to that time (so for example +3 hours would change the value in the $shorttime variable to 15:40). The number of hours I need to add is stored in a variable called $addtime, and this value could be a negative number.

Is this easily doable? Could anyone help?

Thanks :)

like image 384
Ross Avatar asked Aug 05 '11 11:08

Ross


People also ask

How do you convert time from date to string?

The strftime() method takes one or more format codes as an argument and returns a formatted string based on it. We imported datetime class from the datetime module. It's because the object of datetime class can access strftime() method. The datetime object containing current date and time is stored in now variable.

How do you convert date to time?

So, 12 PM is 12/24 = . 5, 6:00 AM is 6/24 = . 25, and so on. So, to convert a time by a given number, you need to divide the number of hours by 24 to get required decimal value: E5 / 24 // convert...

How do I convert a datetime to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.


2 Answers

$time = '2013-01-22 10:45:45';  echo $time = date("H:i:s",strtotime($time)); 

It will give the time 10:45:45 from datetime.

like image 77
Bindiya Patoliya Avatar answered Sep 17 '22 20:09

Bindiya Patoliya


<?PHP  $addhours = 3;  $date = DateTime::createFromFormat('YmdHis', '20110805124000'); $shorttime = $date->format("H:i"); $newdate = $date->add(DateInterval::createFromDateString($addhours . "hours")); $newtime = $newdate->format("H:i");   echo $shorttime . "<br />"; echo $newtime . "<br />"; ?> 

for your reference:

http://www.php.net/manual/en/datetime.createfromformat.php

http://www.php.net/manual/en/dateinterval.createfromdatestring.php

like image 27
Saad Imran. Avatar answered Sep 18 '22 20:09

Saad Imran.