PHP: getting the timestamps and dates for this year, this month and this week

Set the timezone
date_default_timezone_set(“Asia/Shanghai”);
date_default_timezone_set(‘PRC’);//these two methods have the same effect
1
2
To convert a timestamp to a date, you can use date(‘Y-m-s h:i:s’, the specific timestamp)
To convert a date to a timestamp, use strtotime(“date()”).

Timestamp format
//get today’s start timestamp and end timestamp
$beginToday=mktime(0,0,0,date(‘m’),date(‘d’),date(‘Y’));
$endToday=mktime(0,0,0,date(‘m’),date(‘d’)+1,date(‘Y’))-1;

//get yesterday's start timestamp and end timestamp  
$beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));  
$endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;  

//get this week's start timestamp and end timestamp   
$beginThisweek = mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'));  
$endThisweek=time();  

//get last week's start timestamp and end timestamp  
$beginLastweek=mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));  
$endLastweek=mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));  

//get this month's start timestamp and end timestamp  
$beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));  
$endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));  

 //last month's start time:  
$begin_time = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));  
$end_time = strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')));  

$begin_year = strtotime(date("Y",time())."-1"."-1"); //start of this year  
$end_year = strtotime(date("Y",time())."-12"."-31"); //end of this year  

//timestamp difference between now and early morning of the next day  
$time = (strtotime(date('Y-m-d'))+3600*24) - time() ; 

Date format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
echo '<br>上周起始时间:<br>';
echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y"))),"\n";
echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"))),"\n";
echo '<br>本周起始时间:<br>';
echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"))),"\n";
echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"))),"\n";
echo '<br>上月起始时间:<br>';
echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1,1,date("Y"))),"\n";
echo date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,0,date("Y"))),"\n";
echo '<br>本月起始时间:<br>';
echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y"))),"\n";
echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y"))),"\n";
//start of this year
echo date(‘Y-01-01’);
//end date
echo date(‘Y-12-31’);

Original link: https://blog.csdn.net/qq_40018938/article/details/81031414