PHP Date and Time Recipes

No Comments

Coping with dates and instances is a type of issues that may frustrate programmers lots. On the identical time, they’re elementary to software program improvement, used from every part from meta and the way issues are ordered to time-based triggers and much in between.

Dates and instances are susceptible to errors too. Deal with them incorrectly, and so they can confuse end-users and fellow programmers alike.

This can be a fast information to coping with dates and instances particularly within the PHP programming language. It’s meant to be a reference to the most typical wants you’ll have, like formatting and adjusting dates. It’s easy, however it’s seemingly going to cowl 80% of your wants.

Desk of contents

Get the present date and timeAssemble a DateTime object of a selected timeTimezonesLocalizationTime journeyRecurring dates and instancesHow many days in the past?

This analysis is dropped at you by help from Frontend Masters, CSS-Tips’ official studying companion.

Want front-end improvement coaching?

Frontend Masters is the most effective place to get it. They’ve programs on all an important front-end applied sciences. Thinking about going full-stack? Right here’s your finest guess:

Get the present date and time

One factor to know is that the dates and instances could be represented in three types: a timestamp (i.e. epoch time), a DateTime object, and a string.

First up, a recipe to get the present date and time:

<?php

$now = new DateTime();
var_dump($now);

// object(DateTime)#1 (3) {
// [“date”]=>
// string(26) “2021-10-13 22:25:11.790490”
// [“timezone_type”]=>
// int(3)
// [“timezone”]=>
// string(12) “Asia/Jakarta”
// }

This offers a DateTime object that can be utilized to create a date and time string:

<?php

$now = new DateTime();
echo $now->format(“Y-m-d”); // 2021-10-13
echo $now->format(“Y-m-d h:i:s A”); // 2021-10-13 10:10:31 PM

Intuitively, you realize that Y refers back to the 12 months, m refers back to the month, d refers back to the day of the month, and so forth. The total checklist of the parameters could be discovered within the PHP handbook, however I’ll drop a number of the most typical ones right here for reference.

Day of the monthdDay of the month. two digits with main zeros01 – 31jDay of the month with out main zeros1 – 31SIncludes the English suffix.st, nd, rd, th (e.g. 1st, 2nd, third, 4th)WeekdayDAbbreviated textual illustration of a day, in three lettersSun – SatlA full textual illustration of a weekday.Sunday – SaturdayMonthFA full textual illustration of a month, similar to January or MarchJanuary – DecemberMAbbreviated textual illustration of a month, in three lettersJan – DecmNumeric illustration of a month, with main zeros01 – 12nNumeric illustration of a month, with out main zeros1 – 1212 monthsYA full numeric illustration of a 12 months, 4 digitsE.g. 1999 or 2003yA two digit illustration of a yearE.g. 99 or 03TimeAUppercase Ante Meridiem and Submit MeridiemAM or PMg12-hour format of an hour with out main zeros1 – 12h12-hour format of an hour with main zeros01 – 12iMinutes with main zeros00 – 59sSeconds with main zeros00 – 59

The DateTime object could be transformed to a timestamp:

<?php

$now = new DateTime();
echo $now->getTimestamp(); // 1634139081

However we are able to additionally get the present time in timestamp with out developing a DateTime object:

<?php

echo time(); // 1634139081

Assemble a DateTime object of a selected time

What if we need to assemble a DateTime for a specific time, like July 14th, 2011? We will move a formatted string date to the constructor:

<?php

$date = new DateTime(“2011-07-14”);
var_dump($date);

// object(DateTime)#1 (3) {
// [“date”]=>
// string(26) “2011-07-14 00:00:00.000000”
// [“timezone_type”]=>
// int(3)
// [“timezone”]=>
// string(12) “Asia/Jakarta”
// }

The constructor accepts different codecs as nicely:

<?php

$date = new DateTime(“14-07-2011”);
var_dump($date);

// object(DateTime)#1 (3) {
// [“date”]=>
// string(26) “2011-07-14 00:00:00.000000”
// [“timezone_type”]=>
// int(3)
// [“timezone”]=>
// string(12) “Asia/Jakarta”
// }

However watch out with an ambiguous format, like this:

<?php

$date = new DateTime(“07/14/2011”);
var_dump($date);

// object(DateTime)#1 (3) {
// [“date”]=>
// string(26) “2011-07-14 00:00:00.000000”
// [“timezone_type”]=>
// int(3)
// [“timezone”]=>
// string(12) “Asia/Jakarta”
// }

You may suppose that everybody ought to be accustomed to an American date format. However not everyone seems to be and it is likely to be interpreted in another way. Not PostgreSQL.

CREATE TABLE IF NOT EXISTS public.datetime_demo
(
created_at date
);

insert into datetime_demo (created_at) values (’07/12/2011′);

choose created_at from datetime_demo; /* 2011-12-07 */

You could have thought that might return July twelfth, 2011, however it was December seventh, 2011, as a substitute. A greater approach is to make use of an specific format:

<?php

$date = DateTime::createFromFormat(‘m/d/y’, “10/08/21”);
var_dump($date);

//object(DateTime)#2 (3) {
// [“date”]=>
// string(26) “2021-10-08 16:00:47.000000”
// [“timezone_type”]=>
// int(3)
// [“timezone”]=>
// string(12) “Asia/Jakarta”
//}

What if we need to assemble a DateTime object from a timestamp?

<?php

$date = new DateTime();
$date->setTimestamp(1634142890);
var_dump($date);

//object(DateTime)#1 (3) {
// [“date”]=>
// string(26) “2021-10-13 23:34:50.000000”
// [“timezone_type”]=>
// int(3)
// [“timezone”]=>
// string(12) “Asia/Jakarta”
// }

We don’t need to create a DateTime object if we need to convert a timestamp object to a formatted date string:

<?php

echo date(“Y-m-d h:i A”, time()); // 2021-10-14 04:10 PM

Timezones

We will create a DateTime object that features timezone info, like if we’re coping with Pacific Customary Time, Jap Daylight Time, and many others.

<?php

$timezone = new DateTimeZone(“America/New_York”);
$date = new DateTime(“2021-10-13 05:00”, $timezone);
var_dump($date);

// object(DateTime)#1 (3) {
// [“date”]=>
// string(26) “2021-10-13 05:00:00.000000”
// [“timezone_type”]=>
// int(3)
// [“timezone”]=>
// string(16) “America/New_York”
// }

// Jap Daylight Time, for instance: New York
$date = new DateTime(“2021-10-13 05:00 EDT”);
var_dump($date);

// object(DateTime)#2 (3) {
// [“date”]=>
// string(26) “2021-10-13 05:00:00.000000”
// [“timezone_type”]=>
// int(2)
// [“timezone”]=>
// string(3) “EDT”
// }

$date = new DateTime(“2021-10-13 05:00 -04:00”);
var_dump($date);

// object(DateTime)#1 (3) {
// [“date”]=>
// string(26) “2021-10-13 05:00:00.000000”
// [“timezone_type”]=>
// int(1)
// [“timezone”]=>
// string(6) “-04:00”
// }

There are 3 ways to create a DateTime object with timezone info. The timezone_type accepts totally different values for each.

However say we need to convert a date and time that’s displayed in New York’s timezone to show Jakarta’s timezone as a substitute?

<?php

$newYorkTimeZone = new DateTimeZone(“America/New_York”);
$date = new DateTime(“2021-11-11 05:00”, $newYorkTimeZone);
echo $date->format(“Y-m-d h:i A”); // 2021-11-11 05:00 AM
$jakartaTimeZone = new DateTimeZone(“Asia/Jakarta”);
$date->setTimeZone($jakartaTimeZone);
echo $date->format(“Y-m-d h:i A”); // 2021-11-11 05:00 PM

When it’s 05:00 AM in New York, it’s 05:00 PM in Jakarta on the identical day. Jakarta is 12 hours forward of New York on November eleventh 2021. However one month earlier, Jakarta is just 11 hours forward of New York as proven beneath:

<?php

$newYorkTimeZone = new DateTimeZone(“America/New_York”);
$date = new DateTime(“2021-10-11 05:00”, $newYorkTimeZone);
echo $date->format(“Y-m-d h:i A”); // 2021-10-11 05:00 AM
$jakartaTimeZone = new DateTimeZone(“Asia/Jakarta”);
$date->setTimeZone($jakartaTimeZone);
echo $date->format(“Y-m-d h:i A”); // 2021-10-11 04:00 PM

PHP handles Daylight Saving Time for you mechanically.

Localization

This can be a frequent approach to show date and time in the USA:

<?php

$now = new DateTime();
echo $now->format(“m/d/Y h:i A”); // 10/14/2021 03:00 PM

However somebody in France may choose one thing extra frequent to their locale. C’est horrible, they’d complain. For one, no one places the month earlier than month day, besides the U.S. Second, France doesn’t use AM or PM — they use the 24-hour format (e.g. 14:00 as a substitute of two:00 PM) just like the army. That is the way you make a French native comfortable.

<?php

$now = new DateTime();
echo $now->format(“d/m/Y H:i”); // 14/10/2021 15:00

However this requires an intimate information a couple of particular nation or space. As an alternative, we are able to localize the date. To localize a date in PHP, first examine for help for a specific language.

On this instance, we’re utilizing the French. In Ubuntu, set up the French language pack:

$ sudo apt-get set up language-pack-fr

Use the strftime() operate to localize a date:

<?php

setlocale(LC_TIME, “en_US.UTF-8”); // Verify for U.S. English help
echo strftime(“%x %X”); // 10/14/21 03:37:59 PM
setlocale(LC_TIME, “fr_FR.UTF-8”); // Verify for French help
echo strftime(“%x %X”); // 14/10/2021 15:37:31

The entire parameters for strftime are documented in the PHP handbook.

Time journey

Let’s do time journey to the previous and the longer term. First, let’s get acquainted with DateInterval:

<?php

$interval = new DateInterval(“P4M1W2DT2H5M”);

// P 4M 1W 2D T 2H 5M
//
// P = Interval interval (years, months, weeks, days)
// 4M = 4 months
// 1W = 1 week
// 2D = 2 days
//
// T = Time interval (hours, minutes, seconds)
// 2H = 2 hours
// 5M = 5 minutes

The P and T are to separate interval interval and time interval. Right here’s how we are able to journey to the longer term:

<?php

$date = new DateTime(“2021-10-14”);
$interval = new DateInterval(“P2D”); // 2 days
$futureDate = $date->add($interval);
echo $futureDate->format(“Y-m-d”); // 2021-10-16

And right here’s how we return in time:

<?php

$date = new DateTime(“2021-10-14 10:00”);
$interval = new DateInterval(“PT6H”); // 6 hours
$pastDate = $date->sub($interval);
echo $pastDate->format(“Y-m-d H:i”); // 2021-10-14 04:00

If we need to time journey with the title of the weekday, we are able to mix the strtotime() operate and the setTimestamp() methodology of a DateTime object:

<?php

$nextTuesday = strtotime(“subsequent tuesday”);
$date = new DateTime(“2021-10-14”);
$date->setTimestamp($nextTuesday);
echo $date->format(“Y-m-d”); // 2021-10-19

See the total checklist of strtotime() parameters within the PHP docs.

Recurring dates and instances

It’s a typical function in calendar apps to set a reminder that repeats occasionally, like each two days or each week. We will use DatePeriod to characterize a time period:

<?php

$begin = new DateTime(“2021-10-01”);
$finish = new DateTime(“2021-11-01”);
$interval = new DateInterval(“P1W”); // 1 week
$vary = new DatePeriod($begin, $interval, $finish);

// Ranging from October 1st 2021 (inclusive), soar each 1 week
// till November 1st 2021 (unique)
foreach ($vary as $date) {
echo $date->format(“Y-m-d”) . “n”;
}

// 2022-10-01
// 2022-10-08
// 2022-10-15
// 2022-10-22
// 2022-10-29

What number of days in the past?

You understand how companies like Twitter will present that somebody posted X variety of minutes/hours/days/and many others. in the past? We will do the identical factor by calculating how a lot time has elapsed between the the present time and when that motion occurred.

<?php

$date = new DateTime(“2022-10-30”);

$date2 = new DateTime(“2022-10-25”);
$date3 = new DateTime(“2022-10-10”);
$date4 = new DateTime(“2022-03-30”);
$date5 = new DateTime(“2020-03-30”);

operate get_period_ago($endDate, $startDate) {
$dateInterval = $endDate->diff($startDate);

if ($dateInterval->invert==1) {
if ($dateInterval->y > 0) {
return $dateInterval->y . ” years agon”;
} if ($dateInterval->m > 0) {
return $dateInterval->m . ” months agon”;
} if ($dateInterval->d > 7) {
return (int)($dateInterval->d / 7) . ” weeks agon”;
} if ($dateInterval->d > 0) {
return $dateInterval->d . ” days agon”;
}
}
}

echo get_period_ago($date, $date2); // 5 days in the past
echo get_period_ago($date, $date3); // 2 weeks in the past
echo get_period_ago($date, $date4); // 7 months in the past
echo get_period_ago($date, $date5); // 2 years in the past

After getting the DateInterval object from the diff() methodology, be sure that the $startDate variable is previously by checking the invert property. Then examine the y, m, and d properties.

The total checklist of DateInterval object properties could be discovered right here within the PHP docs.

The place do you go from right here?

Now you may have a bit of cheatsheet of frequent PHP recipes for when you end up working with dates and instances. Have to get the present date and time? Possibly you might want to format a date a sure approach, or embrace the native timezone, or evaluate dates. All of that’s proper right here!

There are nonetheless extra strategies and features about date and time that we haven’t mentioned, after all — issues like calendar-related features and whatnot. Remember to hold the PHP Handbook’s Date and Time part shut by for much more use instances and examples.

The submit PHP Date and Time Recipes appeared first on CSS-Tips. You may help CSS-Tips by being an MVP Supporter.

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment