PHP Date Exercises : Count the number of days between current day and birthday
PHP date: Exercise-2 with Solution
Create a simple 'birthday countdown' script, the script will count the number of days between current day and birthday.
Sample Solution:
PHP Code:
<?php
// Set the target date for the birthday using mktime() function: December 31, 2013
$target_days = mktime(0,0,0,12,31,2013);
// Get the current timestamp
$today = time();
// Calculate the difference in seconds between the target date and today's date
$diff_days = ($target_days - $today);
// Convert the difference in seconds to days
$days = (int)($diff_days/86400);
// Print the number of days until the next birthday
print "Days till next birthday: $days days!"."\n";
?>
Output:
Days till next birthday: -1143 days!
Explanation:
The above PHP code calculates the number of days until a specific target date (December 31, 2013) from the current date.
It uses the "mktime()" function to create a timestamp representing the target date, then subtracts this timestamp from the current timestamp obtained using "time()". The difference is converted into days by dividing it by the number of seconds in a day (86400).
Finally, it prints out the number of days until the specified date.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script which will display the copyright information in the following format. To get current year you can use the date() function.
Next: Write a PHP script to print the current date in the following format. To get current date's information you can use the date() function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/php-date-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics