[英]Get first day of week in PHP?
給定日期MM-dd-yyyy
格式,有人可以幫我得到一周的第一天嗎?
這是我正在使用的...
$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));
$day包含一個從 0 到 6 的數字,表示星期幾(星期日 = 0,星期一 = 1 等)。
$week_start包含當前周星期日的日期為 mm-dd-yyyy。
$week_end包含當前周星期六的日期,如 mm-dd-yyyy。
使用strtotime
函數非常簡單:
echo date("Y-m-d", strtotime('monday this week')), "\n";
echo date("Y-m-d", strtotime('sunday this week')), "\n";
2015-03-16
2015-03-22
2015-03-23
2015-03-22
2015-03-30
2015-03-29
像本周這樣的相關描述有其自身的背景。 以下顯示了本周星期一和星期日的輸出,當它是星期一或星期日時:
$date = '2015-03-16'; // monday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
$date = '2015-03-22'; // sunday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
同樣,它在 PHP 版本中略有不同:
2015-03-16
2015-03-22
2015-03-23
2015-03-29
2015-03-16
2015-03-22
2015-03-23
2015-03-22
2015-03-23
2015-03-22
2015-03-23
2015-03-29
2015-03-23
2015-03-29
2015-03-30
2015-03-29
strtotime('this week', time());
替換時間()。 當前日是星期日/星期一時,下一個星期日/上一個星期一的方法將不起作用。
把事情簡單化 :
<?php
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
?>
來源: PHP 手冊
注意:正如一些用戶評論的那樣, $dateTime 值將被修改。
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));
這為您提供給定日期本身的星期幾,其中0
= 星期日和6
= 星期六。 從那里你可以簡單地向后計算你想要的那一天。
這個問題需要一個很好的DateTime答案:-
function firstDayOfWeek($date)
{
$day = DateTime::createFromFormat('m-d-Y', $date);
$day->setISODate((int)$day->format('o'), (int)$day->format('W'), 1);
return $day->format('m-d-Y');
}
var_dump(firstDayOfWeek('06-13-2013'));
輸出:-
string '06-10-2013' (length=10)
這將處理年份邊界和閏年。
編輯:以下鏈接不再在聲明的 PHP 版本上運行。 它在 PHP 5.6 上運行,提高了 strtotime 的可靠性,但並不完美! 表中的結果是 PHP 5.6 的實時結果。
對於它的價值,這里是在確定一致的參考框架時 strtotime 不穩定行為的細分:
http://gamereplays.org/reference/strtotime.php
基本上只有這些字符串才能可靠地為您提供相同的日期,無論您在調用它們時當前處於一周中的哪一天:
strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday");
以下代碼適用於任何自定義日期,只需使用所需的日期格式。
$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) );
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
我用 PHP 5.2.17 結果測試了代碼:
Start: 30-07-2012
End: 05-08-2012
假設星期一為一周的第一天,這有效:
echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));
這個怎么樣?
$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));
這是我用來從任何日期獲取一周的第一天和最后一天的方法。 在這種情況下,星期一是一周的第一天......
$date = date('Y-m-d') // you can put any date you want
$nbDay = date('N', strtotime($date));
$monday = new DateTime($date);
$sunday = new DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
在這里,我將周日作為第一天,周六作為一周的最后一天。
$m = strtotime('06-08-2012');
$today = date('l', $m);
$custom_date = strtotime( date('d-m-Y', $m) );
if ($today == 'Sunday') {
$week_start = date("d-m-Y", $m);
} else {
$week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));
}
if ($today == 'Saturday') {
$week_end = date("d-m-Y", $m);
} else {
$week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));
}
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
輸出 :
開始: 05-08-2012
結束: 11-08-2012
只需使用date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));
這個怎么樣?
$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
$week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
嘗試這個:
function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
$wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
$mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
return date($format, $mon_ts);
}
$sStartDate = week_start_date($week_number, $year);
$sEndDate = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
(來自這個論壇帖子)
這是我發現的最短、最易讀的解決方案:
<?php
$weekstart = strtotime('monday this week');
$weekstop = strtotime('sunday this week 23:59:59');
//echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
?>
strtotime
比new DateTime()->getTimestamp()
快。
$string_date = '2019-07-31';
echo $day_of_week = date('N', strtotime($string_date));
echo $week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
echo $week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
鑒於 PHP 5.3 之前的版本,以下函數為您提供給定日期的一周的第一天(在本例中 - 星期日,2013-02-03):
<?php
function startOfWeek($aDate){
$d=strtotime($aDate);
return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
}
echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');
if($today_day != "Mon")
$start_of_week = date('Ymd', strtotime("last monday"));
if($today_day != "Sun")
$end_of_week = date('Ymd', strtotime("next sunday"));
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));
您必須先獲得下周一,然后才能獲得下周一的“最后一個周一”。 因此,如果給定的日期是星期一,它將返回相同的日期而不是上周的星期一。
如果您希望星期一作為一周的開始,請執行以下操作:
$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));
一個聰明的方法是讓 PHP 處理時區差異和夏令時 (DST)。 讓我告訴你如何做到這一點。
此函數將生成從星期一到星期五的所有日子,包括在內(生成工作日很方便):
class DateTimeUtilities {
public static function getPeriodFromMondayUntilFriday($offset = 'now') {
$now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
$today = $now->setTime(0, 0, 1);
$daysFromMonday = $today->format('N') - 1;
$monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
$saturday = $monday->add(new \DateInterval('P5D'));
return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
}
}
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
print $day->format('c');
print PHP_EOL;
}
這將返回當前周周一至周五的日期時間。 要對任意日期執行相同操作,請將日期作為參數傳遞給DateTimeUtilities ::getPeriodFromMondayUntilFriday
,因此:
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
print $day->format('c');
print PHP_EOL;
}
//prints
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00
正如 OP 所問的那樣,只對星期一感興趣?
$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00
您使用strptime()
解析日期並在結果上使用date()
:
date('N', strptime('%m-%d-%g', $dateString));
<?php
/* PHP 5.3.0 */
date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date
//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));
//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);
?>
(注意:問題中的 MM、dd 和 yyyy 不是標准的 php 日期格式語法 - 我不確定是什么意思,所以我將 $start_date 設置為 ISO 年月日)
另一種方法來做到這一點......
$year = '2014';
$month = '02';
$day = '26';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());
// 0=Sunday 6=Saturday
if($day!=0){
$newdate = $date->getTimestamp() - $day * 86400; //86400 seconds in a day
// Look for DST change
if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
if($old == 0){
$newdate -= 3600; //3600 seconds in an hour
} else {
$newdate += 3600;
}
}
$date->setTimestamp($newdate);
}
echo $date->format('D Y-m-d H:i:s');
獲取本周第一天(星期一)的最簡單方法是:
strtotime("next Monday") - 604800;
其中 604800 - 是 1 周內的秒數(60*60*24*7)。
此代碼下周一獲取並減少 1 周。 此代碼在一周中的任何一天都可以正常工作。 即使今天是星期一。
鑒於我的時區是澳大利亞時區並且strtotime()
討厭英國日期,我發現這非常令人沮喪。
如果當天是星期日,則strtotime("monday this week")
將在后一天返回。
為了克服這個:
注意:這僅適用於澳大利亞/英國日期
$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
這是上周第一天和上周最后一天作為DateTime
對象的單行。
$firstDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 7))
->setTime(0, 0, 0);
$lastDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 1))
->setTime(23, 59, 59);
我已經多次遇到這個問題,並且總是驚訝於日期函數並沒有使這更容易或更清晰。 這是我使用DateTime
類的 PHP5 解決方案:
/**
* @param DateTime $date A given date
* @param int $firstDay 0-6, Sun-Sat respectively
* @return DateTime
*/
function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
$offset = 7 - $firstDay;
$ret = clone $date;
$ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
return $ret;
}
需要克隆以避免更改原始日期。
關於什么:
$date = "2013-03-18";
$searchRow = date("d.m.Y", strtotime('last monday',strtotime($date." + 1 day")));
echo "for date " .$date ." we get this monday: " ;echo $searchRow; echo '<br>';
這不是最好的方法,但我測試過,如果我在本周,我會得到正確的星期一,如果我在星期一,我會得到那個星期一。
我發現這個解決方案很有幫助。 如果不是星期一,就減去上一個星期一。 我使用 $lower_date 作為我從查詢中提取的日期,然后我需要將其與上一個星期一進行協調。
//set this up to go backwards until you find monday
while(date('D',strtotime($lower_date))!='Mon'){
$lower_date = date('Y-m-d', strtotime($lower_date . ' - 1 day')); //increase the upper spec
}
這個准備今天是星期一
function lastMonday(\DateTime $date) {
$timestamp = $date->getTimestamp();
$monday = ( 1 == date( 'N', $timestamp ));
if ($monday) {
return $timestamp;
} else {
return strtotime( 'last monday', $timestamp );
}
}
如果您希望它獲取時間戳而不是 DateTime,請更改前兩行(去掉 date->getTimestamp)將它們更改為此
function lastMonday($timestamp) {
如果你想讓它輸入字符串,請將前兩行更改為此
function lastMonday($dateString) {
$timestamp = strtotime($dateString);
我正在尋找與此類似的解決方案,我終於想出了一些可以在當前一周的每一天返回的東西。
//set current timestamp
$today = time();
//calculate the number of days since Monday
$dow = date('w', $today);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
//calculate timestamp for Monday and Sunday
$monday = $today - ($offset * 86400);
$tuesday = $monday + (1 * 86400);
$wednesday = $monday + (2 * 86400);
$thursday = $monday + (3 * 86400);
$friday = $monday + (4 * 86400);
$saturday = $monday + (5 * 86400);
$sunday = $monday + (6 * 86400);
//print dates for Monday and Sunday in the current week
print date("Y-m-d", $monday) . "\n";
print date("Y-m-d", $tuesday) . "\n";
print date("Y-m-d", $wednesday) . "\n";
print date("Y-m-d", $thursday) . "\n";
print date("Y-m-d", $friday) . "\n";
print date("Y-m-d", $saturday) . "\n";
print date("Y-m-d", $sunday) . "\n";
感謝 dbunic 在此處發布此內容: http : //www.redips.net/php/week-list-current-date/#comments
我用它:
$firstDate = date( 'Y-m-d', strtotime( 'Last Monday', strtotime('-1 week') ));
$lastDate = date( 'Y-m-d', strtotime( 'First Sunday', strtotime('-1 week') ));
希望這對你有幫助!
您也可以使用 Carbon 庫
$dateString = '02-21-2015'; // example in format MM-dd-yyyy
$date = Carbon::createFromFormat('m-d-Y', $dateString);
$date->hour(0)->minute(0)->second(0)->startOfWeek();
$dateString = $date->Format('m-d-Y'); // and you have got a string value "02-16-2015"
應該管用:
/**
* Returns start of most recent Sunday.
*
* @param null|int $timestamp
* @return int
*/
public static function StartOfWeek($timestamp = null) {
if($timestamp === null) $timestamp = time();
$dow = idate('w', $timestamp); // Sunday = 0, Monday = 1, etc.
return mktime(0, 0, 0, idate('m', $timestamp), idate('d', $timestamp) - $dow, idate('Y', $timestamp));
}
輸入和輸出是 unix 時間戳。 使用date
進行格式化。
請注意時間戳數學也可以是一種解決方案。 如果您記得 1970 年 1 月 1 日是星期四,那么可以使用以下公式計算任何給定日期的一周開始時間:
function weekStart($dts)
{ return ($res=$dts-($dts+date('Z',$dts)+259200)%604800)
+(date('I',$dts)-date('I',$res))*3600;
}
它對於任何時間戳和 php 版本都是可預測的,僅對時區和夏令時偏移量使用 date-func ('Z', 'I')。 它產生與以下相同的結果:
strtotime(date('Y-m-d', $dts).' - '.(date('N', $dts)-1.' days');
並提到(最好和最優雅的):
strtotime('monday this week', $dts);
為了擁有最簡單的代碼並從星期一開始數周,我使用了這種方法:
$day = (date('w')+6)%7; //transform week start from sunday to monday
$time = strtotime('-'.$day.' days');
只是簡單的在線回答;)
$mondayThisWeek = new Date($date . 'this week monday');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.