note 112472 modified in datetime.diff by googleguy

From: Date: Thu, 20 Jun 2013 02:18:53 +0000
Subject: note 112472 modified in datetime.diff by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-195295@lists.php.net to get a copy of this message
After wrestling with DateTime::diff for a while it finally dawned on me the problem was both in the formatting of the input string and the formatting of the output. The task was to calculate the duration between two date/times. ### Calculating Duration 1. Make sure you have a valid date variable. Both of these strings are valid: <?php // Example $strStart = '2013-06-19 18:25'; $strEnd = '06/19/13 21:47'; ?> 2. Next convert the string to a date variable ~~~ <?php $dteStart = new DateTime($strStart); $dteEnd = new DateTime($strEnd); ?> ~~~ 3. Calculate the difference ~~~ <?php $dteDiff = $dteStart->diff($dteEnd); ?> ~~~ 4. Format the output ~~~ <?php print $dteDiff->format("%H:%I:%S"); /* Outputs 03:22:00 */ ?> ~~~ [Modified by moderator for clarify] --was-- After wrestling with datetime diff for a while it finally dawned on me the problem was both in the formatting of the input string and the formatting of the output. The task was to calculate the duration between two date/times. ### Calculating Duration 1. Make sure you have a valid date variable. Both of these strings are valid: * 2013-06-19 18:25 * 06/19/13 18:25 2. Next convert the string to a date variable ~~~ $dteStart = new DateTime($strStart); $dteEnd = new DateTime($strEnd); ~~~ 3. Calculate the difference ~~~ $dteDiff = $dteStart->diff($dteEnd); ~~~ 4. Format the output ~~~ # you cannot combine the output thus the following line does not work. print($dteDiff->format("H:I:S")); # DOES NOT WORK # Instead, you have to return each level of the interval print($dteDiff->format("%H").':'); print($dteDiff->format("%I").':'); print($dteDiff->format("%S")); ~~~ http://php.net/manual/en/datetime.diff.php

« previous php.notes (#195295) next »