MOCKSTACKS
EN
Questions And Answers

More Tutorials









php Datetime Class


Create Immutable version of DateTime from Mutable prior PHP


To create \DateTimeImmutable in PHP 5.6+ use:


\DateTimeImmutable::createFromMutable($concrete);

Prior PHP 5.6 you can use:


\DateTimeImmutable::createFromFormat(\DateTime::ISO8601, $mutable->format(\DateTime::ISO8601),
$mutable->getTimezone());

Add or Subtract Date Intervals


We can use the class DateInterval to add or subtract some interval in a DateTime object.
See the example below, where we are adding an interval of 7 days and printing a message on the screen:


$now = new DateTime();// empty argument returns the current date
$interval = new DateInterval('P7D');//this objet represents a 7 days interval
$lastDay = $now->add($interval); //this will return a DateTime object
$formatedLastDay = $lastDay->format('Y-m-d');

Output

this method format the DateTime object and returns a String

echo "Samara says: Seven Days. You'll be happy on $formatedLastDay.";

Output

Samara says: Seven Days. You'll be happy on 2023-06-10.

getTimestamp


getTimeStemp is a unix representation of a datetime object.


$date = new DateTime();
echo $date->getTimestamp();

Output

1685831282

setDate


setDate sets the date in a DateTime object.


$date = new DateTime();
$date->setDate(2016, 7, 25);

Create DateTime from custom format


PHP is able to parse a number of date formats. If you want to parse a non-standard format, or if you want your code to explicitly state the format to be used, then you can use the static DateTime::createFromFormat method:

Object oriented style


$format = "Y,m,d";
$time = "2009,2,26";
$date = DateTime::createFromFormat($format, $time);

Procedural style


$format = "Y,m,d";
$time = "2009,2,26";
$date = date_create_from_format($format, $time);

Conclusion

In this page (written and validated by ) you learned about PHP Datetime Class . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP difference between two dates.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.