I want to take a date and work out its week number.
So far, I have the following. It is returning 24 when it should be 42.
How about using the IntlGregorianCalendar
class?
Requirements: Before you start to use IntlGregorianCalendar
make sure that libicu
or pecl/intl
is installed on the Server.
So run on the CLI:
php -m
If you see intl
in the [PHP Modules]
list, then you can use IntlGregorianCalendar
.
DateTime vs IntlGregorianCalendar:
IntlGregorianCalendar
is not better then DateTime
. But the good thing about IntlGregorianCalendar
is that it will give you the week number as an int
.
Example:
$dateTime = new DateTime('21-09-2020 09:00:00');
echo $dateTime->format("W"); // string '39'
$intlCalendar = IntlCalendar::fromDateTime ('21-09-2020 09:00:00');
echo $intlCalendar->get(IntlCalendar::FIELD_WEEK_OF_YEAR); // integer 39
$date_string = "2012-10-18";
echo "Weeknummer: " . date("W", strtotime($date_string));
Your code will work but you need to flip the 4th and the 5th argument.
I would do it this way
$date_string = "2012-10-18";
$date_int = strtotime($date_string);
$date_date = date($date_int);
$week_number = date('W', $date_date);
echo "Weeknumber: {$week_number}.";
Also, your variable names will be confusing to you after a week of not looking at that code, you should consider reading http://net.tutsplus.com/tutorials/php/why-youre-a-bad-php-programmer/
To get Correct Week Count for Date 2018-12-31 Please use below Code
$day_count = date('N',strtotime('2018-12-31'));
$week_count = date('W',strtotime('2018-12-31'));
if($week_count=='01' && date('m',strtotime('2018-12-31'))==12){
$yr_count = date('y',strtotime('2018-12-31')) + 1;
}else{
$yr_count = date('y',strtotime('2018-12-31'));
}
try this solution
date( 'W', strtotime( "2017-01-01 + 1 day" ) );
Just as a suggestion:
<?php echo date("W", strtotime("2012-10-18")); ?>
Might be a little simpler than all that lot.
Other things you could do:
<?php echo date("Weeknumber: W", strtotime("2012-10-18 01:00:00")); ?>
<?php echo date("Weeknumber: W", strtotime($MY_DATE)); ?>