PHP date handling

Tram Ho

Date handling is extremely important when dealing with posts and posting to the website. For example, if you need to print the date of the post to display in date / month / year or date-month-year, you must know how to use the date functions in PHP to do it. That is the basic problem, there are still many problems and depending on each problem you will have different directions.

1. Setting time_zone in Vietnam

To set time_zone we follow the syntax:

This command will affect all the commands below it so to be sure you should put this command at the top of the program’s file.To set time_zone in Vietnam, use the following command:

To view the list of time zones, use the following code:

2. Format dates with PHP date () function

The date function is used to convert the time to the format that the programmer wants, with the following syntax:

Inside:

  • $format is the format that this function will return
  • $timestamp is the time passed (type INT), by default it will take the current time (is function time ()).

Here I will list some of the most commonly used formats.

  • d: returns date (number)
  • D: returns the day of the month (English)
  • m: returns the month of the year (number)
  • M: Returns the month of the year (English).
  • y: returns the year (the last 2 digits of the year)
  • Y: returns the full year of 4 numbers
  • H: returns the number of hours (24h style)
  • h: return hours (6h type)
  • i: returns the number of minutes
  • s: returns the number of seconds
  • c: Returns the ISO 8601 type of time, which is often used to make the meta publish time tag in SEO

Example: Get current time in date / month / year format – hour: minute: seconds

3. Advanced PHP date handling

  • Convert time to INT type

To convert time to INT type, we use the strtotime($time) :

  • Handling date addition and subtraction with mktime() function

Function mktime() will calculate the exact date by the parameters passed, the syntax is as follows:

Note : This function will return an INT time, so you must use the date () function to convert to the desired format.

Thank you for reading!

References:

https://www.php.net/manual/en/function.date.php

https://freetuts.net/xu-ly-ngay-thang-trong-php-649.html

Share the news now

Source : Viblo