strtotime returning unexpected results, relative timestamps
I am using strtotime
to get some relative timestamps using a string description of the amount of time to shift forward or backward, ie "+1 hour, 15 minutes", "-2 hours, 45 minutes".
This works perfectly:
$ds = strtotime('02/20/11 09:30:00 -1 hour');
However, if it is "-1 hour, 15 minutes", strtotime
seems to be subtracting the hour, then adding the 15 minutes.
I tried it with a comma: http://codepad.org/3dq7c2GM
I came here, saw a previous question about this, and tried it without a comma: http://codepad.org/G8gm8E84
Still no luck. I've tried using the relative parameter: http://codepad.org/nwZ9ZqOv Nothing.
I found my own solution, which is pretty unintuitive, and I am not certain if I am missing something or perhaps even approaching 开发者_如何学JAVAthis incorrectly. The working version ends up being:
$ds = strtotime('02/20/11 09:30:00 -1 hour -15 minutes');
http://codepad.org/O89S3mCj
Am I missing something here? No mention of this kind of behavior in the docs. Also, is there a better way to obtain such relative timestamps using string-based durations?
EDIT
Edited to add the source of these strings - they are coming from the user interface via AJAX. There are form controls that have +/- buttons to increment/decrement the duration in a display field by 15 minute intervals. When they change, the AJAX request fires these values to the server, to be turned into epoch timestamps via strtotime
, which are in turn stored in the database.
I haven't observed that behavior before, but maybe it's because I've always converted my intervals to minutes. I.e.,
$ds = strtotime('02/20/11 09:30:00 -75 minutes');
Where does your time come from or where do you use it after? You might be able to use the MySQL Date manipulations if there's some SQL involved in this.
It makes great sense - it is a interpreter after all.
<?php
$ds = strtotime('02/20/11 09:30:00 -1 hour, 15 minutes');
echo $ds."\n";
echo date('m/d/Y h:i:s a', $ds)."\n";
?>
that one suctracts 1 hour and adds 15 minutes to your time, so if the 15 minutes is turned into negative (as you did, it will do it as you wish)
I would never use strtotime personally - i prefer working with seconds since epoch :-)
精彩评论