Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17586

Subtract 1 day from first day of the year not working as expected

Hi i am trying to subtract 1 day and 1 year from first day of the year using php

Code

        var_dump(date('Y-01-01', strtotime('-1 day')));
        var_dump(date('Y-01-01', strtotime('-1 year')));

Result

string(10) "2019-01-01" string(10) "2018-01-01"

I expect the first result to be 2018-12-31 instead of 2019-01-01 , why only -1 year is working correctly ? please help . thanks in advance.

Upvotes: 2

Views: 53

Answers (1)

Nick
Nick

Reputation: 147206

You are not actually subtracting a day or a year from the beginning of the year, you are subtracting them from the current date. Also, because you are outputting using Y-01-01 format, both dates will always have 1 for the month and day. You need to first generate the first day of the year and then subtract from that and output using Y-m-d format:

$foy = strtotime(date('Y-01-01'));
var_dump(date('Y-m-d', strtotime('-1 day', $foy)));
var_dump(date('Y-m-d', strtotime('-1 year', $foy)));

Output:

string(10) "2018-12-31" 
string(10) "2018-01-01"

Demo on 3v4l.org

Upvotes: 3

Related Questions