Get week number (in the year) from a date PHP

2019-01-08 10:49发布

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.

<?php
$ddate = "2012-10-18";
$duedt = explode("-",$ddate);
$date = mktime(0, 0, 0, $duedt[2], $duedt[1],$duedt[0]);
$week = (int)date('W', $date);
echo "Weeknummer: ".$week;
?>

Is it wrong and a coincidence that the digits are reversed? Or am I nearly there?

标签: php date mktime
12条回答
做自己的国王
2楼-- · 2019-01-08 10:55

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)); ?>
查看更多
做个烂人
3楼-- · 2019-01-08 10:59

Use PHP's date function
http://php.net/manual/en/function.date.php

date("W", $yourdate)
查看更多
SAY GOODBYE
4楼-- · 2019-01-08 10:59

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/

查看更多
虎瘦雄心在
5楼-- · 2019-01-08 11:01

try this solution

date( 'W', strtotime( "2017-01-01 + 1 day" ) );
查看更多
该账号已被封号
6楼-- · 2019-01-08 11:07

This get today date then tell the week number for the week

<?php
 $date=date("W");
 echo $date." Week Number";
 ?>
查看更多
7楼-- · 2019-01-08 11:08

To get the week number for a date in North America I do like this:

function week_number($n)
{
    $w = date('w', $n);
    return 1 + date('z', $n + (6 - $w) * 24 * 3600) / 7;
}

$n = strtotime('2022-12-27');
printf("%s: %d\n", date('D Y-m-d', $n), week_number($n));

and get:

Tue 2022-12-27: 53

查看更多
登录 后发表回答