Forum Moderators: coopster

Message Too Old, No Replies

Subtracting days from date

         

stefansavva

1:15 am on Sep 30, 2003 (gmt 0)

10+ Year Member



Hi there,

I have a date format written in Y-m-d and I need to be able to subtract a set number of days and then display the result.

I know a lot has been written about this but it has beaten me. Can someone help?

Thanks

jatar_k

1:42 am on Sep 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



well,

I would use strtotime [ca.php.net] but it takes a timestamp so...

// split into individual y,m,d
$datearr = split("-",$mydate);

// make timestamp
$timestamp = mktime(0,0,0,$datearr[1],$datearr[2],$datearr[0]);

// increment date, you can alter the number of days obviously
$newtimestamp = strtotime("-5 days",$timestamp);

// change to readable date
$mynewdate = strftime("%Y-%m-%d",$newtimestamp);

that should work

stefansavva

3:40 am on Sep 30, 2003 (gmt 0)

10+ Year Member



Sure I'm missing something because I get an unexpected result when I try the code below.

// get todays date
$mydate = date("Y m d");

// split into individual y,m,d
$datearr = split("-",$mydate);

// make timestamp
$timestamp = mktime(0,0,0,$datearr[1],$datearr[2],$datearr[0]);

// increment date, you can alter the number of days obviously
$newtimestamp = strtotime("-2 days",$timestamp);

// change to readable date
$mynewdate = strftime("%Y-%m-%d",$newtimestamp);

echo $mydate; // outputs 2003 09 30

echo $mynewdate; // outputs 2002-11-28

This code subtracts 2 days which is fine, but then it also subtracts a year and adds two months........

Can you see what I am doing wrong?

jatar_k

5:57 am on Sep 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



if you want to subtract from today then it is even easier

$timestamp = strtotime("-2 days");
$mynewdate = strftime("%Y-%m-%d",$timestamp);

coopster

12:58 pm on Sep 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Easier yet ;)

$mynewdate = strftime("%Y-%m-%d", strtotime("-2 days"));

coopster

1:14 pm on Sep 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



BTW, stefansavva, the reason your code was wrong is because you had no hyphens (-) to split on:
// get todays date
$mydate = date("Y m d");

When you should have had:
$mydate = date("Y-m-d");
// <-- hyphens added

daisho

1:52 pm on Sep 30, 2003 (gmt 0)

10+ Year Member



Hey Jatar you can just do this:

$newtimestamp = strtotime("-5 days",strtotime($mydate));

Since strtotime() I've found to be very good and reliable on parsing any date formate and coming up with the proper timestamp.

daisho.

jatar_k

3:24 pm on Sep 30, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



alright, I know the first one was overly verbose but I was explaining, not doing homework.

bunch o' smart alecs ;)