Handling dates and time is one of the problems that make programmers headaches. At the same time, they are the foundation of software development, from metadata and thing sorting to time-based triggers, and a large number of applications in between.
Date and time are also prone to errors. Improper handling, they can confuse end users and programmer colleagues.
Here is a quick guide on how to handle dates and times in PHP programming language. It is designed as a reference for your most common needs such as date formatting and adjustment. It's simple, but it's likely to cover 80% of your needs.
Table of contents
- Get the current date and time
- Constructing a DateTime object for a specific time
- Time zone
- Localization
- Time Travel
- Date and time that occurs regularly
- How many days ago?
- Next steps?
This study was supported by Frontend Masters, the official learning partner of CSS-Tricks.
Need front-end development training?
Frontend Masters is the best place to learn. They offer courses on all the most important front-end technologies. Interested in becoming a full stack developer? This is your best choice:
Take the course#### Get the current date and time
It should be noted that dates and time can be represented in three forms: timestamps (i.e. epoch time), DateTime object and string.
First, get the code for the current 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 provides a DateTime object that can be used to create date and time strings:
<?php $now = new DateTime(); echo $now-?>format("Ymd"); // 2021-10-13 echo $now->format("Ymd h:i:s A"); // 2021-10-13 10:10:31 PM
You can intuitively understand that Y represents the year, m represents the month, d represents the date in the month, and so on. The complete parameter list can be found in the PHP manual, but I will list some of the most commonly used parameters here for reference.
The DateTime object can be converted to a timestamp:
<?php $now = new DateTime(); echo $now-?>getTimestamp(); // 1634139081
But we can also get the current timestamp without constructing the DateTime object:
<?php echo time(); // 1634139081</pre?><h3> Constructing a DateTime object for a specific time</h3> <p>What if we want to construct a DateTime object for a specific time (for example, July 14, 2011)? We can pass the formatted date string to the constructor:</p> <?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" // } <p>The constructor also accepts other formats:</p> <?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" // } <p>But be aware of ambiguous formats, such as:</p> <?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" // } <p>You might think everyone should be familiar with the date format in the United States. But not everyone is familiar with it, and it may be interpreted differently. PostgreSQL is no exception.</p> CREATE TABLE IF NOT EXISTS public.datetime_demo ( created_at date ); insert into datetime_demo (created_at) values ??('07/12/2011'); select created_at from datetime_demo; /* 2011-12-07 */ <p>You might think this will return July 12, 2011, but it returns December 7, 2011. A better approach is to use an explicit format:</p> <?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" //} <p>What if we want to construct a DateTime object from a timestamp?</p> <?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" // } <p>If we want to convert the timestamp object to a formatted date string, we don't have to create a DateTime object:</p> <?php echo date("Ymd h:i A", time()); // 2021-10-14 04:10 PM</pre?><h3> Time zone</h3> <p>We can create a DateTime object with time zone information, for example, if we are dealing with Pacific Standard Time, Eastern Daylight Time, etc.</p> <?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" // } // For example, Eastern Daylight Time: 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" // } <p>There are three ways to create a DateTime object containing time zone information. timezone_type accepts different values ??for each method.</p> <p>But what if we want to convert dates and times displayed in the New York time zone to display in the Jakarta time zone?</p> <?php $newYorkTimeZone = new DateTimeZone("America/New_York"); $date = new DateTime("2021-11-11 05:00", $newYorkTimeZone); echo $date-?>format("Ymd h:i A"); // 2021-11-11 05:00 AM $jakartaTimeZone = new DateTimeZone("Asia/Jakarta"); $date->setTimeZone($jakartaTimeZone); echo $date->format("Ymd h:i A"); // 2021-11-11 05:00 PM <p>When New York is 5:00 a.m., Jakarta is 5:00 p.m. on the same day. On November 11, 2021, Jakarta is 12 hours faster than New York. But a month ago, Jakarta was only 11 hours faster than New York, as shown below:</p> <?php $newYorkTimeZone = new DateTimeZone("America/New_York"); $date = new DateTime("2021-10-11 05:00", $newYorkTimeZone); echo $date-?>format("Ymd h:i A"); // 2021-10-11 05:00 AM $jakartaTimeZone = new DateTimeZone("Asia/Jakarta"); $date->setTimeZone($jakartaTimeZone); echo $date->format("Ymd h:i A"); // 2021-10-11 04:00 PM <p>PHP automatically processes daylight saving time.</p> <h3>Localization</h3> <p>Here are the common ways to display dates and times in the United States:</p> <?php $now = new DateTime(); echo $now-?>format("m/d/Y h:i A"); // 10/14/2021 03:00 PM <p>But someone in France may prefer a more common format than their region. They may complain, “This is horrible.” First, no one except the United States puts the month before the date. Second, France does not use AM or PM – they use a 24-hour system like the military (e.g. 14:00 instead of 2:00 pm). This is what satisfies the French locals.</p> <?php $now = new DateTime(); echo $now-?>format("d/m/YH:i"); // 14/10/2021 15:00 <p>But this requires a deep understanding of a particular country or region. Instead, we can localize the date. To localize the date, we need to install internationalization support for PHP. In Ubuntu, we can perform this step:</p> $ sudo apt-get install php-intl <p>To display date and time in French, we can use IntlDateFormatter:</p> $locale = "fr_FR.UTF-8"; $formatter = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::SHORT, "Asia/Singapore"); $date = new DateTime("2020-10-10 00:00 UTC"); echo $formatter->format($date); // samedi 10 octobre 2020 à 08:00 <p>You pass the French locale as the first parameter of the IntlDateFormatter.<br> The second parameter is the format of the date. The third parameter is the format of time. The time zone that displays the date and time is in the fourth parameter.</p> <p>In addition to IntlDateFormatter::FULL and IntlDateFormatter::SHORT, other commonly used formats include IntlDateFormatter::NONE and IntlDateFormatter::LONG<br> and IntlDateFormatter::MEDIUM.</p> <p>If you use IntlDateFormatter::NONE for time or third parameter, you do not include the time in the format:</p> $locale = "fr_FR.UTF-8"; $formatter = new IntlDateFormatter($locale, IntlDateFormatter::LONG, IntlDateFormatter::NONE, "Asia/Singapore"); $date = new DateTime("2020-10-10 00:00 UTC"); echo $formatter->format($date); // 10 octobre 2020 <h3>Time Travel</h3> <p>Let's travel time and go back to the past and the future. First, let's understand DateInterval:</p> <?php $interval = new DateInterval("P4M1W2DT2H5M"); // P 4M 1W 2D T 2H 5M // // P = Weekly interval (year, month, week, day) // 4M = 4 months // 1W = 1 week // 2D = 2 days // // T = Time interval (hours, minutes, seconds) // 2H = 2 hours // 5M = 5 minutes</pre?><p> P and T are used to separate the period interval and time interval. Here are how we go to the future:</p> <?php $date = new DateTime("2021-10-14"); $interval = new DateInterval("P2D"); // 2 days $futureDate = $date-?>add($interval); echo $futureDate->format("Ymd"); // 2021-10-16 <p>Here is how we can go back to the past:</p> <?php $date = new DateTime("2021-10-14 10:00"); $interval = new DateInterval("PT6H"); // 6 hours $pastDate = $date-?>sub($interval); echo $pastDate->format("Ymd H:i"); // 2021-10-14 04:00 <p>If we want to use the name of the day of the week for time travel, we can use the setTimestamp() method of the strtotime() function and the DateTime object:</p> <?php $nextTuesday = strtotime("next tutorial"); $date = new DateTime("2021-10-14"); $date-?>setTimestamp($nextTuesday); echo $date->format("Ymd"); // 2021-10-19 <p>See the complete list of strtotime() parameters in the PHP documentation.</p> <h3>Date and time that occurs regularly</h3> <p>A common feature in a calendar application is setting up repeated reminders, such as two days or once a week. We can use DatePeriod to represent a period of time:</p> <?php $start = new DateTime("2021-10-01"); $end = new DateTime("2021-11-01"); $interval = new DateInterval("P1W"); // 1 week$range = new DatePeriod($start, $interval, $end); // Starting from October 1, 2021 (inclusive), skipped every 1 week // until November 1, 2021 (excluding) foreach ($range as $date) { echo $date-?>format("Ymd") . "n"; } // 2022-10-01 // 2022-10-08 // 2022-10-15 // 2022-10-22 // 2022-10-29 <h3>How many days ago?</h3> <p>Did you know that a service like Twitter will show someone’s X minutes/hour/day/etc.? We can do this by calculating the elapsed time between the current time and the time when the operation occurs.</p> <?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"); function get_period_ago($endDate, $startDate) { $dateInterval = $endDate-?>diff($startDate); if ($dateInterval->invert==1) { if ($dateInterval->y > 0) { return $dateInterval->y . " years ago"; } if ($dateInterval->m > 0) { return $dateInterval->m . " months ago"; } if ($dateInterval->d > 7) { return (int)($dateInterval->d / 7) . " weeks ago"; } if ($dateInterval->d > 0) { return $dateInterval->d . " days ago"; } } } echo get_period_ago($date, $date2); // 5 days ago echo get_period_ago($date, $date3); // 2 weeks ago echo get_period_ago($date, $date4); // 7 months ago echo get_period_ago($date, $date5); // 2 years ago <p>After getting the DateInterval object from the diff() method, make sure that the $startDate variable is in the past by checking the invert property. Then check the y, m, and d properties.</p> <p>A complete list of DateInterval object properties can be found in the PHP document here.</p> <h3>Next steps?</h3> <p>Now you have mastered some PHP code snippets that are commonly used when dealing with dates and times. Need to get the current date and time? Maybe you need to format the date somehow, or include the local time zone, or compare the dates. All of this is here!</p> <p>Of course, we haven't discussed more methods and functions about dates and times - such as calendar-related functions, etc. Be sure to check the date and time section of the PHP manual at any time for more use cases and examples.</p>
The above is the detailed content of PHP Date and Time Recipes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.
