Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

Output current week number within month PHP

I have a PHP script to identify the current month and current week within that month.

For today, it should output 501 (i.e. 5th week of the 1st month), however right now it outputs 101.

Can someone explain why this is the case and how I can resolve? I feel I'm missing something obvious.

<?php 
date_default_timezone_set("Europe/London");

function weekOfMonthFunction($date) {
    $firstOfMonth = date("Y-m-01", strtotime($date));
    return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth)));
}

$week = weekOfMonthFunction($date2);
$week = $week + 1;
$month = date("m");
$week_month = $week.$month;

echo $week_month;
question from:https://stackoverflow.com/questions/65886220/output-current-week-number-within-month-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<?php
date_default_timezone_set("Europe/London");

function weekOfMonth() {
    $now = time();
    $week = date('W', $now);
    $firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $now)));
    return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}

$week = weekOfMonth();
$week_month = $week . date("m");

echo $week_month;

501

Try it online!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...