웹 프로그래밍/PHP, Ubuntu, Linux
php - date(날짜시간), strtotime(시간 더하기 빼기)
리게인
2022. 9. 17. 17:05
300x250
반응형
현재시간 기준으로 이전 날짜를 구해봅시다.
현재시간 구하기
$dt = date("Y-m-d H:i:s", time());
echo $dt;
1주일 전 구하기
$dt = date("Y-m-d H:i:s", strtotime("-1 week", time()));
echo $dt;
1달 전 구하기
$dt = date("Y-m-d H:i:s", strtotime("-1 month", time()));
echo $dt;
1년 전 구하기
$dt = date("Y-m-d H:i:s", strtotime("-1 year", time()));
echo $dt;
나머지 시, 분, 초를 더하거나 빼고싶으시면
strotime 함수 안에
+1 hours
-1 hours
+10 minitues
+1 seconds
이런식으로 넣으시면 됩니다.
! 만약 현재시간에 -3개월 한후 +30분을 더하고 싶다면?
(아래 두개는 결과가 같습니다.) time() 에 해당하는 부분을 strtotime으로 한번더 대체하면 됩니다.
당연히 가독성은 (2) 번이 좋겠죠
(1)
$dt = date("Y-m-d H:i:s", strtotime("+30 minutes", strtotime("-3 month", time())));
echo $dt;
(2)
$time_pre_3month = strtotime("-3 month", time());
$dt = date("Y-m-d H:i:s", strtotime("+30 minutes", $time_pre_3month));
echo $dt.'<br>';

참 쉽죠 ㅋ
300x250
반응형