LKB
LKB

Reputation: 1040

How to use PHP's strtotime

I'm new to PHP and kind of struggling with the basics, please excuse the horrible code to come.

What I'm trying to do is parse a date retrieved from an XML file, and see if that date falls on a Monday/Tuesday/etc.

I can't seem to get it right, any help is much appreciated.

<?php

    foreach ($xml as $x)
    {
        $time = strtotime($x->Start);
        echo $time;

       if(date('D', $time) === 'Mon') 
           echo "Booking for Monday";
       else if(date('D', $time) === 'Tue') 
           echo "Booking for Tuesday";
       else if(date('D', $time) === 'Wed')
          echo "Booking for Wednesday"; 
       else if(date('D', $time) === 'Thu')
          echo "Booking for Thursday"; 
       else if(date('D', $time) === 'Fri')
          echo "Booking for Friday";
   }

?>

$time isn't outputting anything, and the only result coming back is "Booking for Thursday" for each XML record (x5) despite only two of the records falling on a Thursday.

If I output the results by:

echo $x->Start;

That works fine and outputs "15/07/2013 9:30:00 a.m.".

Cheers!

Upvotes: 0

Views: 493

Answers (3)

vascowhite
vascowhite

Reputation: 18440

I see you already have an accepted answer, but I would strongly recommend that you take a look at PHP's DateTime classes. They are extremely useful and can make seemingly complex date operations trivial.

In your particular case, I would replace:-

$time = strtotime($x->Start);

with:-

$time = \DateTime::createFromFormat('d/m/Y H:i:s a', $x->Start);

You can then format the date as you wish using the \DateTime::format() method.

Upvotes: 0

Desu
Desu

Reputation: 354

you have to convert your time string($x->Start) to one of the Supported Formats before passing it to the strtotime.

Replacing / with . would change your date to a support format. but double check to be sure.

$time = strtotime(str_replace('/', '.',$x->Start));

Upvotes: 1

bansi
bansi

Reputation: 56982

The date looks like European format d-m-y and uses American format m/d/y seperator.

Note:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

Instead of

$time = strtotime($x->Start);

Try

$time = strtotime(str_replace('/','-',$x->Start));

Additional Info :PHP Manual

Upvotes: 3

Related Questions