0

I need to get the first day of last name everyday. I used to code it like this:

echo date('Ym01',strtotime('last month'));

But today (March 30,2017), it returned the first day of this month, not last month.

I tried echo date('Y-m-d', strtotime('first day of last month')); from this question but it returned 1970-01-01 instead.

Can someone explain to me why the code return date like that?

Community
  • 1
  • 1
hergimerc
  • 9
  • 1
  • My output was, `2017-02-01`, as is expected? CentOS7 w/ PHP5.4.16. Is your system time set correctly? – Matt Clark Mar 30 '17 at 01:28
  • 1
    [no repro](https://3v4l.org/UImIZ) unless you're using a *very* old version of php. – user3942918 Mar 30 '17 at 01:29
  • one thing to remember about dates if it return 1970-01-01 then there is either no date or your format is messed up – Gert Mar 30 '17 at 01:42
  • Thanks everyone. I tried in my local using xampp and it returned the date correctly. Looks like the problem is on the server. Could it be the server system's time not set correctly? But if I only using date('Ymd') or date('Ymd',strtotime('yesterday')) it returned the correct date, today and yesterday. – hergimerc Mar 30 '17 at 02:02

1 Answers1

1

this must work even on older versions of php

<?php

$lastmonth= new datetime();
//formating the date
$lastmonth=$lastmonth->format("Ym01");
//subtracting 1 month to make it last month
$lastmonth=date('Ym01',strtotime($lastmonth . '-1 month'));
echo $lastmonth;

?>

If it doesn't work then the problem is with your server

Gert
  • 360
  • 3
  • 8