mktime()
function in PHP
Definition:
The mktime()
function returns the Unix timestamp for a specific date and time.
Unix timestamp means the number of seconds since January 1, 1970, 00:00:00 GMT.
Syntax:
mktime(hour, minute, second, month, day, year)
- hour (optional) – Default is current hour
- minute (optional) – Default is current minute
- second (optional) – Default is current second
- month (optional) – Default is current month
- day (optional) – Default is current day
- year (optional) – Default is current year
✅ If you don't provide values, it uses the current date and time.
Simple Examples:
1. Create a timestamp for a specific date and time
<?php
$timestamp = mktime(14, 30, 0, 4, 27, 2025);
echo $timestamp;
?>
🔹 This will give the timestamp for April 27, 2025, 2:30 PM.
2. Convert that timestamp into a readable date
<?php
$timestamp = mktime(14, 30, 0, 4, 27, 2025);
echo date("Y-m-d H:i:s", $timestamp);
?>
🔹 Output: 2025-04-27 14:30:00
3. Create today's date at midnight
<?php
$todayMidnight = mktime(0, 0, 0);
echo date("Y-m-d H:i:s", $todayMidnight);
?>
🔹 It will show today's date at 00:00:00.
4. Calculate a date 10 days in the future
<?php
$future = mktime(0, 0, 0, date("m"), date("d")+10, date("Y"));
echo date("Y-m-d", $future);
?>
🔹 Adds 10 days to today's date.
5. Using mktime to handle month overflow
<?php
$date = mktime(0, 0, 0, 13, 10, 2025);
echo date("Y-m-d", $date);
?>
🔹 Even though month 13 doesn't exist, PHP automatically adjusts it:
It will output 2026-01-10
.
Why use mktime()
?
- When you want to create a timestamp manually.
- When you want to add/subtract time easily (like "10 days from now").
- It auto-adjusts invalid dates (like month 13 or day 32).
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.