tags:

views:

55

answers:

3
+1  Q: 

working with dates

Hi. I was wondering if anyone would help with the following:

I have a date called into a function in php. I need to estrapolate the month form this date in order to make some calculation base on the month only.

I really have no idea how do go about it. I have tried few things but none works.

It there anyone who can give a clue?

Appreciated any little help. Francesco

A: 

You need to do two steps: firstly convert the your input string into a datetime object PHP can work with, and secondly, extract the month from that dateime.

$timestamp = strtotime($inputDate);
$month = strftime("%m", $timestamp);

This would give you the month as a two digit number. There are more options in the full documentation for strftime

strtotime() should cope with the vast majority of date formats automatically. If it can't cope with your input then you need to use strptime() and pass in your exact format

iAn
The second line should be `$month = date('n', $timestamp);`. When trying to parse the numbers '01' through '09', PHP treats them as octal numbers, not decimal. date('n') returns the month without a left-padded 0.
Duroth
+2  A: 

You need a unix timestamp to extract that information. Either you already have such a value, or you can get it using strtotime() on a string. The function you need to extract the month is date():

date('n', $timestamp);
soulmerge
strftime() is better than date as it is locale aware
iAn
date() is acceptable here, as I believe author is trying to extract month from standart gregorian calendar and it has 12 months in all locales.
mth
@iAn: Wrong. strftime does not work in this case, since it left-pads single-digit integers with a 0, making PHP treat them as octals.
Duroth
You have intrepreted "calculation" as a purely mathematical operation, in which case an octal value may cause problems, whereas intepretted as a logical operation, in which case it won't
iAn
+1  A: 

Simple

$month= date('n',strtotime($input));
mth
Thank you molevna. Your suggestion worked perfectly.I was thinking this: instead of using month if I want to use a starting day and a ending day (es 01/07 and 31/08) how would in this go?Francescco
francesco
If date comparison is all you want to achieve, then resort to timestamp comparison, i.e. if(strtotime($input1)< strtotime($input2){ //input2 is later than input1 }If you want to compare days of week or months - use same 'date' function with corresponding format parameters ('j' for day of the week in numerical format, and 'n' for month)
mth