是否可以使用PHP的相对日期时间格式获取一周的第一个/最后一个日期?
我试过这样做:
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
Run Code Online (Sandbox Code Playgroud)
如您所见,它不会输出正确的日期.
根据文档,如果我是正确的,这应该是可能的.
我做错了什么吗?
编辑
我需要在远期将PHP的DateTime用于日期.
UPDATE
它现在变得更加陌生.我做了一些测试.
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
Run Code Online (Sandbox Code Playgroud)
Linux 5.3.8
2011-12-01
2011-12-01
2011-11-30
2011-11-30
Run Code Online (Sandbox Code Playgroud)
Jon*_*han 43
我非常喜欢使用Carbon库,这使得这类事情变得非常简单.例如:
use Carbon\Carbon;
$monday = Carbon::now()->startOfWeek()
$sunday = Carbon::now()->endOfWeek()
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望星期日成为您一周的第一天:
use Carbon\Carbon;
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
$sunday = Carbon::now()->startOfWeek()
$saturday = Carbon::now()->endOfWeek()
Run Code Online (Sandbox Code Playgroud)
Jps*_*psy 25
根据文档,格式字符串"第一天"和"最后一天"仅允许数月,而不是数周.见http://www.php.net/manual/en/datetime.formats.relative.php
如果将第一天和最后一天与周语句结合使用,结果要么会破坏解析器,要么是您没想到的(通常是一个月的第一天或最后一天,而不是一周).
您在Win和Linux之间看到的差异可能仅仅是因为不同的错误报告设置.
要获得当前周的第一天和最后一天,请使用:
$date->modify('this week');
$date->modify('this week +6 days');
Run Code Online (Sandbox Code Playgroud)
要获得第50周的第一天和最后一天,请使用:
$date->setISODate(2011, 50);
$date->setISODate(2011, 50, 7);
Run Code Online (Sandbox Code Playgroud)
编辑:
如果要对绝对周数使用modify方法,则必须使用http://www.php.net/manual/en/datetime.formats.compound.php中定义的格式:
$date->modify('2011W50');
$date->modify('2011W50 +6 days');
Run Code Online (Sandbox Code Playgroud)
小智 6
如果一周的第一天是星期一
$date->modify('Monday this week');
Run Code Online (Sandbox Code Playgroud)
否则,如果第一天是星期日
$date->modify('Sunday this week');
Run Code Online (Sandbox Code Playgroud)
因为在不同的国家/地区,一周的第一天可能是星期一或星期日
| 归档时间: |
|
| 查看次数: |
39222 次 |
| 最近记录: |