Timestamps of start and end of month

后端 未结 7 1813
独厮守ぢ
独厮守ぢ 2020-12-03 17:04

How can one get the timestamps of the first and last minutes of any month using PHP?

相关标签:
7条回答
  • 2020-12-03 17:39
    $date = new \DateTime('now');//Current time
    $date->modify("-1 month");//get last month
    $startDate = $date->format('Y-m-01');
    $endDate = $date->format('Y-m-t');
    
    0 讨论(0)
  • 2020-12-03 17:40

    I think better then

    $first_minute = mktime(0, 0, 0, date("n"), 1);
    $last_minute = mktime(23, 59, 0, date("n"), date("t"));
    

    is:

    $first_minute = mktime(0, 0, 0, date("n"), 1);
    $last_minute = mktime(23, 59, 0, date("n") + 1, 0);
    
    0 讨论(0)
  • 2020-12-03 17:40

    This requires PHP > 5.2 and need adjustement for the "minutes" part

    $year = ...;  // this is your year
    $month = ...; // this is your month
    $month = ($month < 10 ? '0' . $month : $month);
    $start = new DateTime($year . '-' . $month . '-01 00:00:00');
    $end = $start->modify('+1 month -1 day -1 minute'); //perhaps this need 3 "->modify"
    echo $start->format('U');
    echo $end->format('U');
    

    (not tested)

    Ref: http://www.php.net/manual/en/class.datetime.php

    0 讨论(0)
  • 2020-12-03 17:43

    Best Way do like this..

    $first_day = date('m-01-Y h:i:s',strtotime("-1 months"));

    $last_day = date('m-t-Y h:i:s',strtotime("-1 months"));

    0 讨论(0)
  • 2020-12-03 17:44

    Use mktime for generating timestamps from hour/month/day/... values and cal_days_in_month to get the number of days in a month:

    $month = 1; $year = 2011;
    $firstMinute = mktime(0, 0, 0, $month, 1, $year);
    $days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $lastMinute = mktime(23, 59, 0, $month, $days, $year);
    
    0 讨论(0)
  • 2020-12-03 17:47

    You can use mktime and date:

    $first_minute = mktime(0, 0, 0, date("n"), 1);
    $last_minute = mktime(23, 59, 59, date("n"), date("t"));
    

    That is for the current month. If you want to have it for any month, you have change the month and day parameter accordingly.

    If you want to generate it for every month, you can just loop:

    $times  = array();
    for($month = 1; $month <= 12; $month++) {
        $first_minute = mktime(0, 0, 0, $month, 1);
        $last_minute = mktime(23, 59, 59, $month, date('t', $first_minute));
        $times[$month] = array($first_minute, $last_minute);
    }
    

    DEMO

    0 讨论(0)
提交回复
热议问题