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:
1 2 | date_default_timezone_set('Tên Time Zone'); |
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:
1 2 | date_default_timezone_set('Asia/Ho_Chi_Minh'); |
To view the list of time zones, use the following code:
1 2 3 4 5 | $timezone = DateTimeZone::listIdentifiers() ; foreach ($timezone as $item){ echo $item . '<br/>'; } |
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:
1 2 | date ($format, $timestamp = 'time()') |
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
1 2 | echo date('d/m/Y - H:i:s'); |
3. Advanced PHP date handling
- Convert time to INT type
To convert time to INT type, we use the strtotime($time)
:
1 2 | echo strtotime(date('Y-m-d H:i:s')); |
- Handling date addition and subtraction with
mktime()
function
Function mktime()
will calculate the exact date by the parameters passed, the syntax is as follows:
1 2 | mktime ($hour, $minute, $second, $month, $day , $year); |
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: