ElToro1966
ElToro1966

Reputation: 901

Trouble with PHP date() - remaining days in month

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

Answers (2)

vascowhite
vascowhite

Reputation: 18440

Using PHP's DateTime class makes this much simpler:-

$now = new \DateTime();
$daysRemaining = (int)$now->format('t') - (int)$now->format('d');

See it working.

Upvotes: 1

Thamilhan
Thamilhan

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

Related Questions