常用php日期函数总结
1. date()
The date() function is used to format a local date and time. It takes one required parameter, which is the format string, and an optional second parameter that specifies a timestamp. The function returns a formatted date string.
$date = date("Y-m-d");
echo "Current date: " . $date;
In the above example, the date() function returns the current date in the format "Y-m-d", which stands for year-month-day. The output will be something like "2022-04-10".
Some commonly used format characters in the format string are:
d - Day of the month, 2 digits with leading zeros (01 to 31)
m - Numeric representation of a month, with leading zeros (01 to 12)
Y - A full numeric representation of a year, 4 digits (e.g., 2022)
H - 24-hour format of an hour with leading zeros (00 to 23)
i - Minutes with leading zeros (00 to 59)
s - Seconds with leading zeros (00 to 59)
2. strtotime()
The strtotime() function is used to convert a human-readable date and time string to a Unix timestamp. It returns the number of seconds passed since January 1, 1970.
$date_string = "2022-04-10";
$timestamp = strtotime($date_string);
echo "Unix timestamp: " . $timestamp;
The above code will output the Unix timestamp corresponding to the date "2022-04-10".
The strtotime() function can also parse relative expressions like "next week", "tomorrow", or "2 months ago". This makes it convenient for manipulating dates and performing calculations.
3. mktime()
The mktime() function is used to get the Unix timestamp for a specific date and time. It takes six parameters for the hour, minute, second, month, day, and year, and returns the Unix timestamp.
$timestamp = mktime(12, 0, 0, 4, 10, 2022);
echo "Unix timestamp: " . $timestamp;
In the above example, the mktime() function returns the Unix timestamp for April 10, 2022, at 12:00 PM.
4. time()
The time() function returns the current Unix timestamp. It is useful for measuring the time elapsed between two events or calculating the age of something.
$now = time();
echo "Current timestamp: " . $now;
The above code will output the current Unix timestamp.
5. getdate()
The getdate() function is used to get an associative array containing information about the current date and time. It can also take a timestamp parameter to retrieve information about a specific date.
$date_info = getdate();
echo "Current year: " . $date_info["year"];
echo "Current month: " . $date_info["mon"];
echo "Current day: " . $date_info["mday"];
In the above example, the getdate() function returns an array containing information about the current date. The year, month, and day are accessed using the array keys "year", "mon", and "mday" respectively.
These are just a few of the many date-related functions available in PHP. Understanding and utilizing these functions will greatly simplify common date and time manipulations in your PHP projects.
Remember to refer to the PHP documentation for more details and examples of usage.