首页 > 开发 > PHP > 正文

php获取指定日期之间的各个周和月的起止时间

2024-05-04 22:17:21
字体:
来源:转载
供稿:网友

根据指定的前后两个日期,计算这两个日期之间各个周的起始时间和结束时间,以及各个月的起始时间和结束时间

日志格式化类 Date.class.php

代码如下:
<?php
class Datefmt{
   function __construct() {}
  /**
   * 根据指定日期获取所在周的起始时间和结束时间
   */
  public 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),
      );
  }
  /**
   * 根据指定日期获取所在月的起始时间和结束时间
   */
  public 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)
      );
  }
  /**
   * 获取指定日期之间的各个周
   */
  public function get_weeks($sdate, $edate) {
    $range_arr = array();
    // 检查日期有效性
    $this->check_date(array($sdate, $edate));
    // 计算各个周的起始时间
    do {
      $weekinfo = $this->get_weekinfo_by_date($sdate);
      $end_day = $weekinfo['week_end_day'];
       $start = $this->substr_date($weekinfo['week_start_day']);
      $end = $this->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;
  }
  /**
  * 获取指定日期之间的各个月
  */
  public function get_months($sdate, $edate) {
    $range_arr = array();
    do {
      $monthinfo = $this->get_monthinfo_by_date($sdate);
      $end_day = $monthinfo['month_end_day'];

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表