[英]PHP - date function to go back in time week by week for a year
我有以下代碼:
$last_week_start = date("Y-m-d",strtotime("monday last week"));
$last_week_end = date("Y-m-d",strtotime("sunday last week"));
for($i=52;$i>0;$i--){
//do stuff with the dates for this week
$last_week_start = date("Y-m-d",strtotime($last_week_start,"-7 days"));
$last_week_end = date("Y-m-d",strtotime($last_week_end,"-7 days"));
}
它給我的最初兩個日期是正確的,但是當我嘗試跳回一周時,我收到一條錯誤消息,指出A non well formed numeric value encountered
。
我不確定為什么會這樣或者我應該如何解決這個問題,任何建議都會很好。
function strotime
在第一個參數中需要一個日期字符串,在第二個參數中需要一個時間戳作為基准時間。
您可以更改代碼以使用DateTime
object 並在此操作日期。
<?php
$last_week_start = new \DateTime("monday last week");
$last_week_end = new \DateTime("sunday last week");
for($i=52;$i>0;$i--){
//do stuff with the dates for this week
$last_week_start->modify("-7 days");
$last_week_end->modify("-7 days");
$last_week_start_formatted = $last_week_start->format("Y-m-d");
$last_week_end_formatted = $last_week_end->format("Y-m-d");
}
strtotime(time, now); Required. Specifies a date/time string
使用這種方式獲得正確的 output
date("Ymd",strtotime("-7 days",strtotime($last_week_start)))
<?PHP
$last_week_start = date("Y-m-d",strtotime("monday last week"));
$last_week_end = date("Y-m-d",strtotime("sunday last week"));
echo $last_week_start." ".$last_week_end;
for($i=52;$i>0;$i--){
//do stuff with the dates for this week
$last_week_start = date("Y-m-d",strtotime("-7 days",strtotime($last_week_start)));
$last_week_end = date("Y-m-d",strtotime("-7 days", strtotime($last_week_end)));
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.