DateTime Object

The DateTime object in PHP simplifies date and time manipulation

In the previous article, we looked at some of the most frequently used date and time functions within PHP. What we haven’t covered is time manipulation. How do you add 2 weeks to a current date-time or how many days are between two dates? That’s where the DateTime object shines.

https://blog.devgenius.io/php-p97-date-and-time-introduction-8174c21a447e

The DateTime Object

DateTime is a class that’s built into PHP. That means that you can instantiate it without doing anything special.

<?php
$datetime = new DateTime();
var_dump($datetime);
/app/95 DateTime Object/index.php:3:
object(DateTime)[1]
  public 'date' => string '2022-11-20 19:33:12.650004' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

The response that we get is pretty simple. It gives us an object with some set properties, such as the datetimezone_type , and timezone. The date is the current date and time.

The first thing that I notice is that the timezone is incorrect for me. To change it, you can create a new time zone with the DateTimeZone class and then use the setTimezone method within the DateTime object to change it.

You can visit PHP’s documentation for a full list of supported timezones.

https://www.php.net/manual/en/timezones.php?source=post_page—–1191e4b457c1——————————–

<?php
$datetime = new DateTime();

$timezone = new DateTimeZone("America/New_York");
$datetime->setTimezone($timezone);

var_dump($datetime);
/app/95 DateTime Object/index.php:7:
object(DateTime)[1]
  public 'date' => string '2022-11-20 14:37:21.736311' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/New_York' (length=16)

This time, I get the correct timezone.

Now that we have everything correctly configured, if we wanted to display the current date and time in a particular format, we could. Read my previous article on all of the available format strings.

<?php
$datetime = new DateTime();

$timezone = new DateTimeZone("America/New_York");
$datetime->setTimezone($timezone);

echo $datetime->format("F d, Y");
November 11, 2022

It extracted out of the date string the current date and then used the correct format to format it. What if we wanted to change the date and not use the default one? We could have passed that in our constructor when creating it.

<?php
$datetime = new DateTime("11/5/2022 5:00 AM");

var_dump($datetime);
/app/95 DateTime Object/index.php:6:
object(DateTime)[1]
  public 'date' => string '2022-11-05 05:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

We can also modify the date property with the modify method. It accepts our standard formatter string.

<?php
$datetime = new DateTime("11/5/2022 5:00 AM");
var_dump($datetime);

$datetime->modify("11/10/2022 7:00 AM");
var_dump($datetime);
/app/95 DateTime Object/index.php:5:
object(DateTime)[1]
  public 'date' => string '2022-11-05 05:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

/app/95 DateTime Object/index.php:9:
object(DateTime)[1]
  public 'date' => string '2022-11-10 07:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

We can also use the setDate and setTime methods to modify the date and time.

<?php
$datetime = new DateTime("11/5/2022 5:00 AM");
var_dump($datetime);

$datetime->setDate(2022, 11, 20);
var_dump($datetime);

$datetime->setTime(14, 20, 30);
var_dump($datetime);
/app/95 DateTime Object/index.php:30:
object(DateTime)[1]
  public 'date' => string '2022-11-05 05:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

/app/95 DateTime Object/index.php:32:
object(DateTime)[1]
  public 'date' => string '2022-11-20 05:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

/app/95 DateTime Object/index.php:34:
object(DateTime)[1]
  public 'date' => string '2022-11-20 14:20:30.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

There is one interesting thing about the setDatesetTime and even setTimezone methods. Each of them return the DateTime object that was instantiated.

I know that we haven’t covered chaining until now, but it’s quite simple. When then method returns the object that it’s part of, it means that you can chain on other methods.

<?php
$datetime = new DateTime("11/5/2022 5:00 AM");
var_dump($datetime->setDate(2022, 11, 20));

What do you think this will look like? It should theoretically just be the DateTime object we instantiated, right?

/app/95 DateTime Object/index.php:40:
object(DateTime)[3]
  public 'date' => string '2022-11-20 14:20:30.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

That’s right. Now, let’s look at chaining those methods.

<?php
$datetime = new DateTime("11/5/2022 5:00 AM");
$datetime->setDate(2022, 11, 20)
    ->setTimezone(new DateTimeZone("America/New_York"))
    ->setTime(14, 20, 30);

var_dump($datetime);
/app/95 DateTime Object/index.php:41:
object(DateTime)[3]
  public 'date' => string '2022-11-20 14:20:30.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/New_York' (length=16)

Remember that each of these methods returns an object. It’s important to set these methods in order then. For example, let’s move the setTimezone method after the setTime method. Do you think we’ll get the same result?

<?php
$datetime = new DateTime("11/5/2022 5:00 AM");
$datetime->setDate(2022, 11, 20)
    ->setTime(14, 20, 30)
    ->setTimezone(new DateTimeZone("America/New_York"));
var_dump($datetime);

The result is not intuitive. We don’t get the time that we just posted.

/app/95 DateTime Object/index.php:41:
object(DateTime)[3]
  public 'date' => string '2022-11-20 09:20:30.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/New_York' (length=16)

How did we get 9:20:30? Because it translated that time once we changed the timezone. So, set your timezone before.

DateTime Operations

This is where the DateTime object starts to show its true colors. These operations will be between two objects. We can look at comparing two dates to see if one date comes after another, before another or if they’re the same.

<?php
$datetime1 = new DateTime("11/5/2022");
$datetime2 = new DateTime("11/4/2022");
var_dump($datetime1 > $datetime2);
var_dump($datetime1 < $datetime2);
var_dump($datetime1 == $datetime2);

/app/95 DateTime Object/index.php:46:boolean true
/app/95 DateTime Object/index.php:47:boolean false
/app/95 DateTime Object/index.php:48:boolean false

As you can see, in the first operation, we see that the first date is greater than the second date.

And now, the difference between two date/times. This is why we’re here after all. Seems complicated. But it’s not.

<?php
$datetime_from = new DateTime("01/20/1978 4:00:32");
$datetime_to   = new DateTime("11/20/2022 22:01:00");

$difference = $datetime_to->diff($datetime_from);
var_dump($difference);

Just remember the from and to dates. You’re going to want to subtract from your to object. In other words, that’s the one you’ll use to call your diff method.

/app/95 DateTime Object/index.php:55:
object(DateInterval)[7]
  public 'y' => int 44
  public 'm' => int 10
  public 'd' => int 0
  public 'h' => int 18
  public 'i' => int 0
  public 's' => int 28
  public 'f' => float 0
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 1
  public 'days' => int 16375
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

You get some pretty cool numbers instantaneously. You can see that these two dates differ by 44 years, 10 months, 18 hours, and 28 seconds. It also tells us the total number of days between two dates, which is 16,375.

We don’t have to store the result in its own separate object. We can just chain on.

<?php
$datetime_from = new DateTime("01/20/1978 4:00:32");
$datetime_to   = new DateTime("11/20/2022 22:01:00");
var_dump($datetime_to->diff($datetime_from)->format("The number of years passed is: %Y"));
/app/95 DateTime Object/index.php:
60:string 'The number of years passed is: 44' (length=33)

We also need to be able to easily add and subtract from a date. What if we wanted to add 10 days to a date or subtract 1 year and 65 days?

The add method represents a DateInterval object. The DateInterval object requires a string to be passed to the constructor. It follows the following format: P (for period) Qty (for the amount that you want) and Type (Years, Months, Hours, etc). You’ll always start with a P followed by the remainder: P1Y means a period of 1 year. P2Y3H means a period of 2 years and 3 hours. These are the available options

Y number of years.

M Number of months.

D number of days.

H number of hours.

I number of minutes.

S number of seconds.

F number of microseconds.

<?php
$datetime = new DateTime("11/23/2022 22:01:00");
$datetime->add(new DateInterval("P10D"));
var_dump($datetime);
/app/95 DateTime Object/index.php:65:
object(DateTime)[6]
  public 'date' => string '2022-12-03 22:01:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

And similarly, let’s subtract 1 year and 65 days from our example.

<?php
$datetime = new DateTime("11/23/2022 22:01:00");
$datetime->sub(new DateInterval("P1Y65D"));
var_dump($datetime);
/app/95 DateTime Object/index.php:70:
object(DateTime)[3]
  public 'date' => string '2021-09-19 22:01:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

If you need to subtract time, you’ll need to prefix your DateInterval string with a PT, for example PT10H.

<?php
$datetime = new DateTime("11/23/2022 22:01:00");
$datetime->sub(new DateInterval("PT10H"));
var_dump($datetime);
/app/95 DateTime Object/index.php:75:
object(DateTime)[6]
  public 'date' => string '2022-11-23 12:01:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/London' (length=13)

And there we go, you’re a DateTime professional. There are other operations that we wont get into because most of the time this is where you’ll live.

https://github.com/dinocajic/php-youtube-tutorials?source=post_page—–1191e4b457c1——————————–

Date and Time

CALCULATE INTERVALS & PERFORM DATE ARITHMETIC IN PHP

PHP – P97: DATE AND TIME INTRODUCTION

PHP offers robust tools for working with dates and times. DateTime objects provide powerful date manipulation capabilities.

DateTime Object

The DateTime object in PHP simplifies date and time manipulation

PHP – P98: datetime object

How do you add 2 weeks to a current date-time or how many days are between two dates? That’s where the DateTime object shines.

Dependency Management Intro

A CORNERSTONE OF MODERN SOFTWARE DEVELOPMENT PRACTICES

PHP – P99: DEPENDENCY MANAGEMENT

Dependency management ensures smooth integration of software components. It’s essential for maintaining software stability and updates.

Leave a Reply