[php] 날짜 시간 관련 다양한 예제

[php] 날짜 시간 관련 다양한 예제 updated_at: 2023-03-17 04:32

날짜/시간 관련 다양한 예

날짜, 시간 더하고 빼기

$date = strtotime("now");

$update = date("Y-m-d", strtotime("+1 seconds", $date));  // 1초후
$update = date("Y-m-d", strtotime("-1 seconds", $date));  // 1초전

$update = date("Y-m-d", strtotime("+1 minutes", $date));  // 1분후
$update = date("Y-m-d", strtotime("-1 minutes", $date));  // 1분전

$update = date("Y-m-d", strtotime("+1 hours", $date));  // 1시간후
$update = date("Y-m-d", strtotime("-1 hours", $date));  // 1시간전



$update = date("Y-m-d", strtotime("+1 day", $date));  // 1일후
$update = date("Y-m-d", strtotime("-1 day", $date));  // 1일전

$update = date("Y-m-d", strtotime("+1 week", $date));  // 1주후

$update = date("Y-m-d", strtotime("+1 months", $date));  // 1달후

$update = date("Y-m-d", strtotime("+1 years", $date));  // 1년후

$update = date("Y-m-d", strtotime("+1 years +2 months +3 days +4 hours", $date));  // 1년 2달 3일 4시간 후

그달의 몇번째 주인지 구하는 함수

<?php
function weekOfMonth($timestamp, $year, $month, $day){
  if ($month == 0 || $year == 0 || $day == 0){
    if ($timestamp == 0) return 0;  // error
    else list($month, $year) = explode(',', date('m,Y', $timestamp));
  }else if ($month == 0 || $year == 0 || $day == 0){
    return 0;  // error
  }else{
    $timestamp = mktime(0, 0, 0, $month, $day, $year);
  }
  
  return date('W', $timestamp) - date('W', mktime(0, 0, 0, $month, 1, $year)) + 1;
}
$timestamp = time();
$year = date("Y");
$month = date("m");
$day = date("d");
$w = date(w, mktime(0,0,0,$month, $day, $year));
$start_timestamp=mktime(0,0,0,$month,$day-$w,$year);
$last_timestamp=mktime(0,0,-1,$month,$day+7-$w,$year);
$start_day = date("m월d일", $start_timestamp);
$last_day = date("m월d일", $last_timestamp);
echo "오늘은 ".$month."월의 ".weekOfMonth($timestamp, $year, $month, $day)."주 입니다.";
echo weekOfMonth($timestamp, $year, $month, $day)."주의 시작일은 ".$start_day." 이고 마지막일은 ".$last_day." 입니다.";
?>

응용예

<?php
function weekOfMonth($timestamp, $year, $month, $day){
    if ($month == 0 || $year == 0 || $day == 0){
        if ($timestamp == 0) return 0;  // error
        else list($month, $year) = explode(',', date('m,Y', $timestamp));
    }else if ($month == 0 || $year == 0 || $day == 0){
        return 0;  // error
    }else{
        $timestamp = mktime(0, 0, 0, $month, $day, $year);
    }
    
    return date('W', $timestamp) - date('W', mktime(0, 0, 0, $month, 1, $year)) + 1;
}
$timestamp = time();
$year = date("Y");
$month = date("m");$set_last_timestamp = mktime(0,0,-1,$month+1,1,$year);
for($i=0; $i < 6; $i++){
  $day = $i*7 + 1;
  $start_timestamp=mktime(0,0,0,$month,$day,$year);
  $last_timestamp=mktime(0,0,-1,$month,$day+7,$year);
  $start_day = date("m월d일", $start_timestamp);
  $last_day = date("m월d일", $last_timestamp);
    if($last_timestamp >= $set_last_timestamp){
      echo $month."월의 ".weekOfMonth($timestamp, $year, $month, $day)."주의 시작일은 ".$start_day." 이고 마지막일은 ".date("m월d일", $set_last_timestamp)." 입니다.";
      break;
    }
  echo $month."월의 ".weekOfMonth($timestamp, $year, $month, $day)."주의 시작일은 ".$start_day." 이고 마지막일은 ".$last_day." 입니다.";
}
?>

결과

07월의 1주의 시작일은 07월01일 이고 마지막일은 07월07일 입니다.
07월의 2주의 시작일은 07월08일 이고 마지막일은 07월14일 입니다.
07월의 3주의 시작일은 07월15일 이고 마지막일은 07월21일 입니다.
07월의 4주의 시작일은 07월22일 이고 마지막일은 07월28일 입니다.
07월의 5주의 시작일은 07월29일 이고 마지막일은 07월31일 입니다.

월의 마지막 날짜 구하기

예제 1

다음월을 1일에서 -1 초를 하여 날짜를 구하는 방식

$last_timestamp=mktime(0, 0, -1, $month + 1, 1, $year);
date("m월d일", $start_timestamp);

예제 2 (추천)

date에서 제공하는 't'를 사용하는 방식

 $lastday =  date('t', strtotime());

그달의 몇번째주인지 구하는 함수

5월의 3째주, 6월의 1째주 이런식으로 몇째주인지 구하는 함수 입니다.

<?php

/**
  * Determine the week of the month for a date
  *
  * The date in question may be given as a timestamp
  * or as separate day, month and year numbers
  *
  * @param int $timestamp The date in question 
  * @param int $year The year of the date in question
  * @param int $month The month of the date in question
  * @param int $day The day of the date in question
  *
  * @return int The week of the month that the given
  *            date falls within, or zero if error
  *
  */
function weekOfMonth($timestamp=0, $year=0, $month=0, $day=0)
{

   // bunch of junk to figure out parameters
   // skip to last line to see what you really
   // wanted... 

   if ($month == 0 || $year == 0 || $day == 0)
   {
     if ($timestamp == 0)
         return 0;  // error
     else
         list($month, $year) = explode(',', date('m,Y', $timestamp));
   }
   else if ($month == 0 || $year == 0 || $day == 0)
     return 0;  // error
   else
     $timestamp = mktime(0, 0, 0, $month, $day, $year);

   // not much to it; just subtract week of year
   // for the first of the month from the week of
   // the year for the target timestamp

   return date('W', $timestamp) 
       - date('W', mktime(0, 0, 0, $month, 1, $year));

}
?>

두 날짜간에 일일 간격(일자별) 으로 날짜 출력하기

일자별로 출력

$s_day = 20100328;
$e_day = 20100403;
$date["Y"] = substr($s_day, 0, 4);
$date["m"] = substr($s_day, 4, 2);
$date["d"] = substr($s_day, 6, 2);
while(true){
  echo $s_day."";
  if($s_day > $e_day) break;
  $s_day =  date("Ymd", mktime(0,0,0,$date["m"],$date["d"],$date["Y"]));
  $date["d"]++;
}

출력결과

20100328
20100329
20100330
20100331
20100401
20100402
20100403
20100404

두 날짜 사이의 일수 구하기

$from = new \DateTime( '2023-03-17' ); // 끝나는 날짜를 변수에 담는다.
$to = new \DateTime( '2023-04-14' ); //diff 또는 date_diff로 차이를 구한다.

// echo $from -> diff( $to )->days;
echo date_diff( $from, $to )->days;

출력결과

28

두개의 날짜(시간) 비교하여 차이 구하기 + 특정 달까지 달로 증감하기

<?php
function timeDiff($ts1, $ts2) {
  if ($ts1 < $ts2) {
    $temp = $ts1;
    $ts1 = $ts2;
    $ts2 = $temp;
  }
  $format = 'Y-m-d H:i:s';
  $ts1 = date_parse(date($format, $ts1));
  $ts2 = date_parse(date($format, $ts2));
  $arrBits = explode('|', 'year|month|day|hour|minute|second');
  $arrTimes = array(0, 12, date("t", $temp), 24, 60, 60);
  foreach ($arrBits as $key => $bit) {
    $diff[$bit] = $ts1[$bit] - $ts2[$bit];
    if ($diff[$bit] < 0) {
      $diff[$arrBits[$key - 1]]--;
      $diff[$bit] = $arrTimes[$key] - $ts2[$bit] + $ts1[$bit];
    }
  }
  return $diff;
}
$start_date = mktime(0, 0, 0, 10, 1, 2007);
$end_date = mktime(0,0,0,date("m")-1, 1, date("Y")); 
$date_diff_array = timeDiff($start_date, time());

$init_i = $date_diff_array['year']*12 + $date_diff_array['month'];
$thismonth = date("m");
$thisyear = date("Y");
for($i=0; $i<=$init_i; $i++){
  echo date("Ym", mktime(0,0,0,$thismonth-$i, 1, $thisyear))."";

}
?>
평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글