How would i convert a format like:
13 hours and 4 mins ago
Into something i can use in php to further convert?
try
strtotime('13 hours 4 mins ago', time())
http://php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/datetime.formats.php
http://www.php.net/manual/en/datetime.formats.relative.php
To get a unix timestamp fromt he current server time:
$timestamp = strtotime("-13 hours 4 minutes");
Try the DateInterval class - http://www.php.net/manual/en/class.dateinterval.php - which you can then sub() from a regular DateTime object.
Do it the hard way:
$offset = (time() - ((60 * 60) * 13) + (4 * 60));
Working Example: http://codepad.org/25CJPL76
Explanation:
(60 * 60) is 1 hour, then * 13 to make 13 hours, plus (4 * 60) for the 4 minutes, minus the current time.
What i usually do is create several constants to define the values of specific time values like so:
define("NOW",time());
define("ONE_MIN", 60);
define("ONE_HOUR",ONE_MIN * 60);
define("ONE_DAY", ONE_HOUR * 24);
define("ONE_YEAR",ONE_DAY * 365);
and then do something like:
$offset = (NOW - ((ONE_HOUR * 13) + (ONCE_MIN * 4)));
in regards to actually parsing the string, you should look at a javascript function and convert to PHP, the source is available from PHP.JS:
http://phpjs.org/functions/strtotime:554
Use strtotime(), and perhaps date() later, e.g.:
$thetime = strtotime('13 hours 4 minutes ago');
$thedate = date('Y-m-d', $thetime);
Related
so, I substract two dates:
$d = $start->diff($end);
and now I want to get the date in seconds (not the second parameter). I know it can be done with a native Php function - but it only works above 1970. I know I have to somehow operate with format() method, but I dont get it...
You could access the public properties of the DateInterval class and do some math on it:
$seconds = $d->s + ($d->i * 60) + ($d->h * 3600) + ($d->d * 86400) + ($d->m * 2592000); // and so on
but once we get into the months there will be variance by +/- 2 days unless we stick to an arbitrary definition of a month as 2592000 secs (30 days).
You can also use the difference of the two UNIX timestamps from the DateTime objects (but you will end up having problems with the dates being less than year of 1970):
$seconds = $end->getTimestamp() - $start->getTimestamp();
The following seems to work, although I feel there should be a better way.
$dateIntrvl = $start->diff($end);
$days = $dateIntrvl->format('%a');
$hours = $dateIntrvl->format('%h');
$mins = $dateIntrvl->format('%i');
$secs = $dateIntrvl->format('%s');
$totalSeconds = ($days * 24 * 60 * 60) + ($hours * 60 * 60) + ($mins * 60) + $secs;
And yes, it seems to be working for dates earlier than 1970.
How about using a class DateTime / DateTimeImmutable to create current DateTime instance, then add your DateInterval $d by using the add() method, and then using the getTimestamp() method.
(new \DateTimeImmutable())->add($d)->getTimestamp()
To get number of seconds from now, just subtract time().
(new \DateTimeImmutable())->add($d)->getTimestamp() - \time()
There is the following variable:
$datetime = '2012-09-09 01:40';
I need to extract hours and minutes, and then to transform them into minutes. In this example, I would need to get 100 (1 hr 40 min = 60 min + 40 min). How can I quickly do this using PHP functions?
The strtotime() and date() functions are not recommended anymore. Use the DateTime class.
$datetime = '2012-09-09 01:40';
$d = new DateTime($datetime);
var_dump( $d->format('G') * 60 + $d->format('i') );
$string = '2012-09-09 01:40';
$epoch = strtotime($string);
echo date('i', $epoch) + (60 * date('H', $epoch));
Outputs 100
Basically what happens here is the string date gets converted to Unix/Epoch time. Then, using date() it adds the number of minutes (i) to 60 times the number of hours (h).
$datetime = strtotime('2012-09-09 01:40');
$hour = date('H',$datetime);
$min = date('i',$datetime);
echo ($hour*60 + $min);
You can use preg_split like this:
$parts=preg_split("/(\d\d):(\d\d)/",$datetime,-1,PREG_SPLIT_DELIM_CAPTURE);
$mins=($parts[1]*60)+$parts[2];
Now $mins=100 when $datetime is like in your post
This question already has answers here:
Work out the percentage of the day that has elapsed
(5 answers)
Closed 9 years ago.
Im trying to get the current time elapsed percentage of todays time. It can be either javascript or php. How can I do that ?
Use a Date object and some arithmetic. Convert the components of the current day into a equivalent unit (such as seconds), find their sum, and divide that by the number of that unit per day.
For example, the following is a solution in JavaScript.
var d = new Date();
var pctDayElapsed = (d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds() + d.getMilliseconds()/1000)/86400;
Note that this approach piggybacks on the browser's localization. Your result will depend on the browser's timezone.
I would use the current time to calculate the number of seconds that has elapsed today and then divide that by 86400 (the number of seconds in a day), and of course multiply that by 100 to get it from decimal to percent.
Here is an answer in PHP:
$now=time();
$today=strtotime(date("m/d/Y"));
$seconds=$now-$today;
$day=24*60*60;//seconds in a day;
$percent=$seconds/$day*100;
OR
$hours=date('G')*60*60;
$minutes=date('i')*60;
$seconds=date('s');
$day=24*60*60;//seconds in a day;
$percent=($hours+$minutes+$seconds)/$day*100
<?php
$timestamp = time();
$hours = intval(date("G", $timestamp));
$minutes = intval(date("i", $timestamp));
$seconds = intval(date("s", $timestamp));
$proportion_elapsed = ($hours * 60 * 60 + $minutes * 60 + $seconds) /
(24 * 60 * 60);
printf("%0.4F of the day has elapsed.", $proportion_elapsed);
?>
This works as long as there are 86,400 seconds in a day, which may not be true due to Daylight Savings time or leap seconds.
Round down to the beginning of the day by dividing the current time by 86400, then multiply that integer value by 86400. Then take the difference of the current time (in seconds of course) and then divide 86400 into it. Lastly, multiply by 100.
Edit: mod works more efficiently
Pseudocode:
MidnightDays = (TimeInSeconds % 86400) * 86400;
Percentage = (TimeInSeconds - MidnightDays) / 86400 * 100;
This question already has answers here:
Convert seconds to Hour:Minute:Second
(30 answers)
Closed 8 years ago.
is there a built in functionality in php to convert seconds to hh:mm:ss
There's no built in function, this will work though:
function formatSeconds($seconds){
$hours = $seconds / (60 * 60);
$minutes = ( $seconds - $hours * 60 * 60) / 60;
$seconds = $seconds - $hours * 60 * 60 - $minutes * 60 - $seconds;
return $hours.':'.$minutes.':'.$seconds;
}
$seconds=3672;
echo date_create()->add(new DateInterval("PT{$seconds}S"))
->diff(new DateTime)
->format('%H:%I:%S');
Just another way that works.
I needed an answer to this recently and I ran across this web page concerning inserting a phpdate into a mysql table. (I bet this is also what you're dealing with.) It seems to indicate that you can use something like
$mysqldate = date( 'H:i:s', time());
This seems to work fine even if the number of seconds exceeds a 24 hour period.
Yes, the strftime() function (manual):
print(strftime("%H:%M:%S", $_seconds_ ))
2009-10-05 18:11:08
2009-10-05 18:07:13
This should generate 235,how to do it ?
With DateTime objects, you can do it like this:
$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );
$diffInSeconds = $date2->getTimestamp() - $date->getTimestamp();
You can use strtotime() to do that:
$diff = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
A similar approach is possible with DateTime objects, e.g.
$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );
$diff = $date2->getTimestamp() - $date->getTimestamp();
PHP Date Time reference is helpful for things like this: PHP Date Time Functions
strtotime() is probably the best way.
$seconds = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
For those worrying about the limitations of using timestamps (i.e. using dates before 1970 and beyond 2038), you can simply calculate the difference in seconds like so:
$start = new DateTime('2009-10-05 18:11:08');
$end = new DateTime('2009-10-05 18:07:13');
$diff = $end->diff($start);
$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->h * 60 * 60;
$minsInSecs = $diff->i * 60;
$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->s;
echo $seconds; // output: 235
Wrote a blog post for those interested in reading more.
Because of unix epoch limitations, you could have problems compairing dates before 1970 and after 2038. I choose to loose precision (=don't look at the single second) but avoid to pass trough unix epoch conversions (getTimestamp). It depends on what you are doing to do...
In my case, using 365 instead (12*30) and "30" as mean month lenght, reduced the error in an usable output.
function DateIntervalToSec($start,$end){ // as datetime object returns difference in seconds
$diff = $end->diff($start);
$diff_sec = $diff->format('%r').( // prepend the sign - if negative, change it to R if you want the +, too
($diff->s)+ // seconds (no errors)
(60*($diff->i))+ // minutes (no errors)
(60*60*($diff->h))+ // hours (no errors)
(24*60*60*($diff->d))+ // days (no errors)
(30*24*60*60*($diff->m))+ // months (???)
(365*24*60*60*($diff->y)) // years (???)
);
return $diff_sec;
}
Note that the error could be 0, if "mean" quantities are intended for diff. The PHP docs don't speaks about this...
In a bad case, error could be:
0 seconds if diff is applied to time gaps < 1 month
0 to 3 days if diff is applied to time gaps > 1 month
0 to 14 days if diff is applied to time gaps > 1 year
I prefer to suppose that somebody decided to consider "m" as 30 days and "y" as 365, charging "d" with the difference when "diff" walk trough non-30-days months...
If somebody knows something more about this and can provide official documentation, is welcome!
strtotime("2009-10-05 18:11:08") - strtotime("2009-10-05 18:07:13")
The solution proposed by #designcise is wrong when "end date" is before "start date".
Here is the corrected calculation
$diff = $start->diff($end);
$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->format('%r%h') * 60 * 60;
$minsInSecs = $diff->format('%r%i') * 60;
$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->format('%r%s');
A simple and exact solution (exemplifying Nilz11's comment):
$hiDate = new DateTime("2310-05-22 08:33:26");
$loDate = new DateTime("1910-11-03 13:00:01");
$diff = $hiDate->diff($loDate);
$secs = ((($diff->format("%a") * 24) + $diff->format("%H")) * 60 +
$diff->format("%i")) * 60 + $diff->format("%s");