If you want to convert a Timespan given in Seconds into an DateInterval Object you could dot the following:
<?php
$dv = new DateInterval('PT'.$timespan.'S');
?>
but wenn you look at the object, only the $dv->s property is set.
As stated in the documentation to DateInterval::format
The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".
If you still want to calculate the seconds into hours / days / years, etc do the following:
<?php
$d1 = new DateTime();
$d2 = new DateTime();
$d2->add(new DateInterval('PT'.$timespan.'S'));
$iv = $d2->diff($d1);
?>
$iv is an DateInterval set with days, years, hours, seconds, etc ...
La classe DateInterval
(PHP 5 >= 5.3.0)
Introduction
Représente un intervalle de dates.
Un intervalle stocke un nombre fixe de durées (en années, mois, jours, heures, etc.) ou une chaîne relative à une durée dans un format compréhensible par le constructeur de la classe DateTime.
Synopsis de la classe
Propriétés
- y
-
Année.
- m
-
Numéro du mois.
- d
-
Numéro du jour.
- h
-
L'heure.
- i
-
Les minutes.
- s
-
Les secondes.
- invert
-
Vaut 1 si l'intervalle représente une période de temps négative, 0 sinon. Voir la méthode DateInterval::format().
- days
-
Si l'objet DateInterval a été créé avec la méthode DateTime::diff(), alors ce sera le nombre total de jours entre la date de début et la date de fin. Sinon, days vaudra
FALSE.
Sommaire
- DateInterval::__construct — Crée un nouvel objet DateInterval
- DateInterval::createFromDateString — Configure un objet DateInterval à partir des parties d'une chaîne
- DateInterval::format — Formate l'intervalle
When using DateInterval('P3M') on 30th of November you get March instead of Ferbuary.
It would be nice that when converting a DateInterval to a string, the interval specification used to construct the object is returned (like "P2W").
I need this to serialize a DateInterval object in order to store it in a postgres DB.
This class became available in PHP 5.3. It is not present in 5.2 or earlier releases. I found this out the hard way when you PHP scripts stopped working when I deployed them onto a Yahoo server. Yahoo has 5.2 while my machine hosts 5.3.
