目录
  • 一、时间戳和日期互相转换
  • 二、PHP获取今日、昨日、上周、本周、上月、本月的起始时间戳
  • 三、获取当前周的每天的起始时间
  • 四、获取周的起始时间
    • 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;
                }

                PHP中的时间戳相关函数非常丰富,可以满足开发者在处理时间相关问题时的各种需求。其中,time()函数可以获取当前时间戳,strtotime()函数可以将字符串转换为时间戳,date()函数可以将时间戳格式化为指定的日期格式。除此之外,还有mktime()函数可以根据指定的时间参数获取时间戳,microtime()函数可以获取当前时间的微秒数等。掌握这些函数可以帮助开发者更加高效地处理时间相关的问题,提高开发效率。

                声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。