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
553 views
in Technique[技术] by (71.8m points)

php - Finding date range for current week, month and year

Suppose I have a date available with me:

2011-04-05 (i.e., 5th April, 2011)

I want to find date range for Current Week, Month and Year

Current Week:  3rd April to 9th April
Current Month: 1st April to 30 April
Current Year:  1st Jan to 31 Dec

I do understand that current year would be always 1st Jan to 31Dec, but what about current month and week, How can I find it?

Edit:

How can I find date, which is 10 days earlier or later from a given date. Example:

Suppose today's date is 6th April, 2011 10 day's earlier: 28 March, 2011 10 day's later: 15 April, 2011

Any thoughts on this, guys?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
 function rangeMonth ($datestr) {
   date_default_timezone_set (date_default_timezone_get());
   $dt = strtotime ($datestr);
   return array (
     "start" => date ('Y-m-d', strtotime ('first day of this month', $dt)),
     "end" => date ('Y-m-d', strtotime ('last day of this month', $dt))
   );
 }

 function rangeWeek ($datestr) {
   date_default_timezone_set (date_default_timezone_get());
   $dt = strtotime ($datestr);
   return array (
     "start" => date ('N', $dt) == 1 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('last monday', $dt)),
     "end" => date('N', $dt) == 7 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('next sunday', $dt))
   );
 }

 print_r (rangeMonth('2011-4-5')); // format: YYYY-M-D
 print_r (rangeWeek('2011-4-5'));

output for rangeMonth()

Array
(
    [start] => 2011-04-01
    [end] => 2011-04-30
)

output for rangeWeek()

Array
(
    [start] => 2011-04-04
    [end] => 2011-04-08
)

Notice: functions like getdate(), date(), etc. throw Warning if default time zone is not set in php.ini.


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

...