Chorn Sokun's Weblog

Conquer inner fear, push it to the limit!

PHP date diff

with 2 comments

I call out for an excuse for not practicing PHP enough recent year; with just a simple date_diff could knock me out :) not to open my complain of having different version of PHP to check before using a function(s) I got a request from a friend to help workout how many days from two given date.

Now if I have two date string (it is what we get from form post right?)

// fixed format as I don't want to deal with complicate of different world format :(
$day1 = "26/03/2009";
$day2 = "28/03/2009";
// now I need to know how many days does it take from day1 to day2
// PHP 4.x; ignore my out of date PHP skill this is how I did it
$break_day1_apart = explode('/', $day1);
$break_day2_apart = explode('/', $day2);
$day1_number_form = $break_day1_apart[2].$break_day1_apart[1].$break_day1_apart[0];
$day2_number_form = $break_day2_apart[2].$break_day2_apart[1].$break_day2_apart[0];

$day_diff = abs((int)$day2_number_form - (int)$day1_number_form);

// and it should work by theory
echo $day_diff; 

Suck ! what would you do instead?

About these ads

Written by Chorn Sokun

July 4, 2009 at 11:37 am

2 Responses

Subscribe to comments with RSS.

  1. [...] I found an interesting PHP related post by Chorn Sokun entitled “PHP date diff“. The author was trying to calculate the number days between two give dates. At the end of [...]

  2. Sokun, there is a bug in you code. If you test with the following dates, you’d know why:

    $day1 = “29/07/2009″;
    $day2 = “01/08/2009″;

    This is my answer to your question “How would you do it?”

    kenno

    July 4, 2009 at 4:21 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: