php - 获取一周的第一个/最后一个日期

标签 php datetime

是否可以使用 PHP 的 Relative Date Time format 获取一周的第一个/最后一个日期? ?

我已经尝试过:

date_default_timezone_set('Europe/Amsterdam');
$date = new DateTime();

$date->modify('first day of this week'); // to get the current week's first date
echo $date->format('Y-m-d'); // outputs 2011-12-19

$date->modify('first day of week 50'); // to get the first date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18

$date->modify('last day of this week'); // to get the current week's last date
echo $date->format('Y-m-d'); // outputs 2011-12-17

$date->modify('last day of week 50'); // to get the last date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18

尽你所能see它没有输出正确的日期。

根据the docs如果我是正确的,这应该是可能的。

我做错了什么吗?

编辑

我需要使用 PHP 的 DateTime 作为遥远 future 的日期。

更新

现在变得更加陌生了。我又做了一些测试。

Windows PHP 5.3.3

2011-12-01

Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (first day of week 50) at position 13 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 9
2011-12-01
2011-11-30

Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (last day of week 50) at position 12 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 15
2011-11-30

Linux 5.3.8

2011-12-01
2011-12-01
2011-11-30
2011-11-30

最佳答案

我非常喜欢使用 Carbon图书馆,这使得这类事情变得非常容易。例如:

use Carbon\Carbon;

$monday = Carbon::now()->startOfWeek()
$sunday = Carbon::now()->endOfWeek()

或者,如果您希望星期天是一周的第一天:

use Carbon\Carbon;

Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);

$sunday = Carbon::now()->startOfWeek()
$saturday = Carbon::now()->endOfWeek()

关于php - 获取一周的第一个/最后一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8541466/

相关文章:

sql - 有趣的SQL连接日期之间的日期

php - 如何使用 Jquery 或 PHP 打印关联的 div 内容和 css

php - 为什么 count 比 $count 差

php - 使用 PDO 序列化数据是否危险

Python3.5 对象和 json.dumps() 输出

c# - 在MVC3(C#)中将GMT日期时间转换为用户本地时间并将本地时间转换为GMT日期时间

php - 如何在 laravel 控制台命令中显示异常跟踪?

php - 从下拉列表中选择时自动更改页面

javascript - 如何将 mysql 日期转换为 var obj [新日期?

sql - 将 Varchar 列转换为日期时间格式 - SQL Server