Reputation: 901
I am trying to calculate the remaining days in a month from any given day. I have the following code:
<?php
date_default_timezone_set("UTC");
echo $timestamp = date('Y-m-d');
echo " - ";
echo $daysInMonth = (int)date('t', $timestamp);
echo " - ";
echo $thisDayInMonth = (int)date('j', $timestamp);
echo " - ";
echo $daysRemaining = $daysInMonth - $thisDayInMonth;
?>
The output is: 2016-12-14 - 31 - 1 - 30
I have also tried with date('d', $timestamp), but it still returns 1 for the present day even though it should be 14. Why am I getting 1 for the present day? Thanks.
My PHP version is 5.4.45.
Upvotes: 0
Views: 513
Reputation: 18440
Using PHP's DateTime class makes this much simpler:-
$now = new \DateTime();
$daysRemaining = (int)$now->format('t') - (int)$now->format('d');
Upvotes: 1
Reputation: 13313
Just add strtotime to the timestamp variable since date function needs second parameter as integer value. But when you supply formatted date, it is considered string.
date_default_timezone_set("UTC");
echo $timestamp = date('Y-m-d');
echo " - ";
echo $daysInMonth = (int)date('t', strtotime($timestamp));
echo " - ";
echo $thisDayInMonth = (int)date('j', strtotime($timestamp));
echo " - ";
echo $daysRemaining = $daysInMonth - $thisDayInMonth;
Output:
2016-12-14 - 31 - 14 - 17
Upvotes: 2