PHP获取时间戳、获取天周月的起始时间、指定时间所在周、指定时间的各个周等相关函数

该文详细介绍了如何在PHP中进行时间戳与日期的互相转换,包括获取今日、昨日、上周、本周、上月、本月的起始时间戳,以及当前周、指定日期的周、月的起始和结束时间等。此外,还提供了获取指定日期是周几、日期段内特定周几的日期等实用功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、时间戳和日期互相转换

二、PHP获取今日、昨日、上周、本周、上月、本月的起始时间戳

三、获取当前周的每天的起始时间

四、获取周的起始时间

1、根据指定时间获取所在周的起始时间和结束时间

2、通过时间戳 获取某周的开始时间和结束时间 

五、获取指定日期是周几

六、通过某个日期段内的周几获取对应的日期  开始日期 结束日期 

七、获取指定日期之间的各个周

八、获取指定日期之间的各个月

九、根据指定日期获取所在月的起始时间和结束时间

十、获取指定年份的每个月的起始时间

 十一、获取指定月份的起止时间戳

十二、最近七天的起始时间戳

十三、最近七天的每天的起始时间戳

十四、获取指定月份月初和月末的时间戳

十五、获取本周的每一天时间

 1、获取未来一周的时间

2、获取本周每一天的时间


一、时间戳和日期互相转换

// 获取时间戳
$date = time(); // 获取当前时间戳
$date = mktime(0, 0, 0, 10, 10, 2020); // 获取指定时间的时间戳 2020年10月10日0时0分0秒

// 日期转换为时间戳
$date = "2019-08-08 08:08:08";
$timestamp = strtotime($date);

// 将时间戳转换成日期
$date = time();
echo date('Y-m-d', $date); // 输出格式化的日期(年-月-日)

// 将时间戳转换为时间格式
$date = time();
echo date('H:i:s', $date); // 输出格式化的时间(小时:分钟:秒)

// 日期格式化
$date = time();
echo date('Y-m-d H:i:s', $date); // 输出格式化的日期时间(年-月-日 小时:分钟:秒)

// 将时间戳转换为星期
$date = time();
echo date('l', $date); // 输出星期几的完整文本形式(例如:Sunday)

// 将时间戳转换为月份
$date = time();
echo date('F', $date); // 输出月份的完整文本形式(例如:January)


二、PHP获取今日、昨日、上周、本周、上月、本月的起始时间戳

//今日开始时间戳和结束时间戳
$beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
$endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

//昨日起始时间戳和结束时间戳
$beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
$endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;

//本周起始时间戳和结束时间戳
$startTime = mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'));
$endTime = mktime(23,59,59,date('m'),date('d')-date('w')+7,date('y'));

//上周起始时间戳和结束时间戳
$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'));

//本月起始时间戳和结束时间戳
$beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
$endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));

//上月起始时间戳和结束时间戳
$begin_time = date('Y-m-01 00:00:00',strtotime('-1 month'));
$end_time = date("Y-m-d 23:59:59", strtotime(-date('d').'day'));

//获取当前季度
$season = ceil((date('m'))/3);
//本季度起始时间戳和结束时间戳
$starTime=mktime(0, 0, 0,$season*3-3+1,1,date('Y'));
$endTime = mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'));

//当年起始时间戳和结束时间戳
$startTime  = strtotime(date("Y",time())."-1"."-1"); 
$overTime  = strtotime(date("Y",time())."-12"."-31");  

三、获取当前周的每天的起始时间

function getDay(){
    $timestr = time();    //当前时间戳
    $now_day = date('w',$timestr);  //当前是周几

    //获取周一
    $monday_str = $timestr - ($now_day-1)*60*60*24;
    $monday = date('Y-m-d', $monday_str);

    //获取周日
    $sunday_str = $timestr + (7-$now_day)*60*60*24;
    $sunday = date('Y-m-d', $sunday_str);

    for($i=0;$i<7;$i++)  
    {  
        $arr[$i]['start']=strtotime(date('Y-m-d',strtotime($monday.'+'.$i.'day')));  
        $arr[$i]['end']=strtotime(date('Y-m-d',strtotime($monday.'+'.$i.'day')). " 24:00:00");  
    }
    return $arr; 
}

四、获取周的起始时间

1、根据指定时间获取所在周的起始时间和结束时间

/**
* @param data 日期
*/
function get_weekinfo_by_time($date) {
    $idx = strftime("%u", strtotime($date));
    $mon_idx = $idx - 1;
    $sun_idx = $idx - 7;
    return array(
      'week_start_day' => strftime('%Y-%m-%d', strtotime($date) - $mon_idx * 86400),
      'week_end_day' => strftime('%Y-%m-%d', strtotime($date) - $sun_idx * 86400),
      );
}

2、通过时间戳 获取某周的开始时间和结束时间 

/**
* @param time 时间
* @param first 表示每周星期一为开始日期 0表示每周日为开始日期
*/
function getWeekMyActionAndEnd($time = '', $first = 1)
{
  //当前日期
  if (!$time) $time = time();
  $sdefaultDate = date("Y-m-d", $time);
  //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
  $w = date('w', strtotime($sdefaultDate));
  //获取本周开始日期,如果$w是0,则表示周日,减去 6 天
  $week_start = date('Y-m-d', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));
  //本周结束日期
  $week_end = date('Y-m-d', strtotime("$week_start +6 days"));
  return array("week_start" => $week_start, "week_end" => $week_end);
}

五、获取指定日期是周几

/**
* @param data 日期
*/
function DateToWeek($date){
    //强制转换日期格式
    $date_str=date('Y-m-d',strtotime($date));

    //封装成数组
    $arr=explode("-", $date_str);
     
    //参数赋值
    //年
    $year=$arr[0];
     
    //月,输出2位整型,不够2位右对齐
    $month=sprintf('%02d',$arr[1]);
     
    //日,输出2位整型,不够2位右对齐
    $day=sprintf('%02d',$arr[2]);
     
    //时分秒默认赋值为0;
    $hour = $minute = $second = 0;   
     
    //转换成时间戳
    $strap = mktime($hour,$minute,$second,$month,$day,$year);
     
    //获取数字型星期几
    $number_wk=date("w",$strap);
     
    //自定义星期数组
    $weekArr=array("周日","周一","周二","周三","周四","周五","周六");
     
    //获取数字对应的星期
    return $weekArr[$number_wk];
}

六、通过某个日期段内的周几获取对应的日期  开始日期 结束日期 

/**
* @param data 日期 array(start_date,end_data)
*/
function getDateByWeek($data)
{
	$start_date = strtotime($data['start_date']);
	$end_date = strtotime($data['end_date']);
	$days = ($end_date - $start_date) / 86400;
	$weekArr = array('周日','周一','周二','周三','周四','周五','周六');
	$newDate = array();
	// 组建数组格式 $dataWeek['日期'] => 星期
	for ($i=0; $i < $days; $i++) { 
		$num_week = date('w',$start_date+($i*86400));
		$dateWeek[date('Y-m-d',$start_date+($i*86400))] = $weekArr[$num_week];
	}
	// 查找两个数组的交集,即获取提交的星期对应的日期
	$newDate=array_intersect($dateWeek,$data['items']);
	// 获取数组中的键值(日期),并组成一个新数组
	$date = array_keys($newDate);
	return $date;
}

七、获取指定日期之间的各个周

/**
* @param sdate 开始日期
* @param edate 结束日期
*/
function get_weeks($sdate, $edate) {
    $range_arr = array();
    // 检查日期有效性
    check_date(array($sdate, $edate));
    // 计算各个周的起始时间
    do {
      $weekinfo = get_weekinfo_by_date($sdate);
      $end_day = $weekinfo['week_end_day'];
       $start = substr_date($weekinfo['week_start_day']);
      $end = substr_date($weekinfo['week_end_day']);
      $range = "{$start} ~ {$end}";
      $range_arr[] = $range;
       $sdate = date('Y-m-d', strtotime($sdate)+7*86400);
    }while($end_day < $edate);
    return $range_arr;
}

/**
  * 检查日期的有效性 YYYY-mm-dd
  * @param array $date_arr
  * @return boolean
  */
function check_date($date_arr) {
    $invalid_date_arr = array();
    foreach ($date_arr as $row) {
      $timestamp = strtotime($row);
      $standard = date('Y-m-d', $timestamp);
      if ($standard != $row) $invalid_date_arr[] = $row;
    }
    if ( ! empty($invalid_date_arr)) {
      die("invalid date -> ".print_r($invalid_date_arr, TRUE));
    }
} 

/**
   * 截取日期中的月份和日
   * @param string $date
   * @return string $date
   */
   function substr_date($date) {
    if ( ! $date) return FALSE;
    return date('m-d', strtotime($date));
  }

/**
   * 根据指定日期获取所在周的起始时间和结束时间
   */
   function get_weekinfo_by_date($date) {
    $idx = strftime("%u", strtotime($date));
    $mon_idx = $idx - 1;
    $sun_idx = $idx - 7;
    return array(
      'week_start_day' => strftime('%Y-%m-%d', strtotime($date) - $mon_idx * 86400),
      'week_end_day' => strftime('%Y-%m-%d', strtotime($date) - $sun_idx * 86400),
      );
  }

八、获取指定日期之间的各个月

/**
* @param sdate 开始日期
* @param edate 结束日期
*/
function get_months($sdate, $edate) {
    $range_arr = array();
    do {
      $monthinfo = get_monthinfo_by_date($sdate);
      $end_day = $monthinfo['month_end_day'];
       $start = substr_date($monthinfo['month_start_day']);
      $end = substr_date($monthinfo['month_end_day']);
      $range = "{$start} ~ {$end}";
      $range_arr[] = $range;
       $sdate = date('Y-m-d', strtotime($sdate.'+1 month'));
    }while($end_day < $edate);
    return $range_arr;
  }

/**
   * 截取日期中的月份和日
   * @param string $date
   * @return string $date
   */
   function substr_date($date) {
    if ( ! $date) return FALSE;
    return date('m-d', strtotime($date));
  }

/**
   * 根据指定日期获取所在月的起始时间和结束时间
   */
   function get_monthinfo_by_date($date){
    $ret = array();
    $timestamp = strtotime($date);
    $mdays = date('t', $timestamp);
    return array(
      'month_start_day' => date('Y-m-1', $timestamp),
      'month_end_day' => date('Y-m-'.$mdays, $timestamp)
      );
  }

九、根据指定日期获取所在月的起始时间和结束时间

/**
* @param date 日期
*/
function get_monthinfo_by_date($date){
    $ret = array();
    $timestamp = strtotime($date);
    $mdays = date('t', $timestamp);
    return array(
      'month_start_day' => date('Y-m-1', $timestamp),
      'month_end_day' => date('Y-m-'.$mdays, $timestamp)
      );
}

十、获取指定年份的每个月的起始时间

/**
* @param year 年份
*/
function getMonthByDate($year)
{
	// $year = '2019';
	$yeararr = [];
	$month = [];
	for ($i=1; $i <=12 ; $i++) { 
		$yeararr[$i] = $year.'-'.$i;
	}
	foreach ($yeararr as $key => $value) {
		$timestamp = strtotime($value );
		$start_time = date( 'Y-m-1 00:00:00', $timestamp );
		$mdays = date( 't', $timestamp );
		$end_time = date( 'Y-m-' . $mdays . ' 23:59:59', $timestamp );

		$month[$key]['start_time'] = strtotime($start_time);
		$month[$key]['end_time'] = strtotime($end_time);
	}
	return $month;
}

 十一、获取指定月份的起止时间戳

/**
* 获取指定月份的时间戳
* @param $date Y-m
*/
function get_month_begin_end($date){

    // $date = '2018-11';

    $data['begin_time'] = strtotime($date);  //指定月份月初时间戳  
    $data['end_time'] = mktime(23,59,59,date('m',strtotime($date))+1,00);   //指定月份月末时间戳

    return $data;
}

十二、最近七天的起始时间戳

第一天的开始时间戳,第七天的结束时间戳


$data['begin'] = strtotime(date('Y-m-d 00:00:00', strtotime('-7 days')));
$data['end'] = strtotime(date('Y-m-d 23:59:59',time()));
return $data;

十三、最近七天的每天的起始时间戳

每天开始时间戳(00:00:00)、每天结束时间戳(23:59:59)

$timestamps = [];
for ($i = 0; $i < 7; $i++) {
    // 当前日期减去$i天
    $date = date("Y-m-d", strtotime("-{$i} days"));

    // 当天开始时间戳
    $startTimestamp = strtotime($date . " 00:00:00");

    // 当天结束时间戳
    $endTimestamp = strtotime($date . " 23:59:59");

    // 将开始和结束时间戳放入一个子数组中
    $timestamps[] = [
        'date' => $date,
        'start' => $startTimestamp,
        'end' => $endTimestamp
    ];
}

十四、获取指定月份月初和月末的时间戳

获取指定月份的开始时间戳和结束时间戳,只需传入年月即可(2018-01,2018-1两种格式都可以)

$data['sel_time'] = '2018-11';
$data['begin_time'] = strtotime($data['sel_time']);        //指定月份的开始时间戳
$data['end_time'] = mktime(23,59,59,date('m',strtotime($data['sel_time']))+1,00);  //指定月份月末时间戳 
 
echo $data['begin_time']."<br>".$data['end_time'];

结果

十五、获取本周的每一天时间

 1、获取未来一周的时间

public function getWeek()
{
   for($i=0;$i<7;$i++)  
   {  
       $arr[$i]=date('Y-m-d',strtotime(date('Y-m-d').'-'.$i.'day'));  
   }  
 
   return json($arr); 
}

2、获取本周每一天的时间

public function getDay()
{
    $timestr = time();    //当前时间戳
    $now_day = date('w',$timestr);  //当前是周几

    //获取周一
    $monday_str = $timestr - ($now_day-1)*60*60*24;
    $monday = date('Y-m-d', $monday_str);

    //获取周日
    $sunday_str = $timestr + (7-$now_day)*60*60*24;
    $sunday = date('Y-m-d', $sunday_str);

    for($i=0;$i<7;$i++)  
    {  
        $arr[$i]=date('Y-m-d',strtotime($monday.'+'.$i.'day'));  
    }
    return json($arr); 
    // echo "星期一: $monday\n";
    // echo "星期天: $sunday\n";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

下页、再停留

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值