728x90
이번달의 마지막날은 언제이지?, 다음주 월요일 날짜를 구해야해!
PHP로 날짜를 계산하다 보면 이런 요구사항들을 자주 만나게 됩니다.
DateTime 객체를 사용하거나 직접 날짜를 계산하는 방법도 있지만, 간단하게 해결할 수 있는 함수가 있습니다.
바로 strtotime() 입니다.
strtotime()은 String To Time 의 약자로 사람이 이해 할 수 이는 날짜/시간 형식의 문자열을 유닉스 타임스탬프로 변환합니다.
예제
<?php
// 'now'는 현재 시간을 의미합니다.
$now_timestamp = strtotime("now");
echo date("Y-m-d H:i:s", $now_timestamp); // 예: 2023-10-27 15:10:00
echo "<br>";
// 특정 날짜 문자열을 타임스탬프로 변환
$specific_timestamp = strtotime("2025-01-01");
echo date("Y-m-d", $specific_timestamp); // 2025-01-01
?>
타임스태프는 숫자일 뿐이므로 사람이 알아보기 쉬운 날짜 형식으로 바꾸려면 date() 함수와 함께 사용해야합니다.
시연화면
예제 아래와같이 상대적인 시간을 쉽게 계산이 가능합니다.
day, week, month, year, hour, minute, second 등을 사용할 수 있습니다.
<?php
echo "현재 시간: " . date("Y-m-d H:i:s") . "<br>";
echo "1일 뒤: " . date("Y-m-d", strtotime("+1 day")) . "<br>";
echo "2주 전: " . date("Y-m-d", strtotime("-2 weeks")) . "<br>";
echo "3달 뒤: " . date("Y-m-d", strtotime("+3 months")) . "<br>";
echo "1년 전: " . date("Y-m-d", strtotime("-1 year")) . "<br>";
echo "10시간 30분 뒤: " . date("Y-m-d H:i:s", strtotime("+10 hours +30 minutes")) . "<br>";
?>
시연화면
예제코드
next, last, first, last 등의 키워드를 요일이나 월과 조합할 수 있습니다.
<?php
echo "다음 주 월요일: " . date("Y-m-d", strtotime("next Monday")) . "<br>";
echo "지난 주 금요일: " . date("Y-m-d", strtotime("last Friday")) . "<br>";
echo "다음 달 첫째 날: " . date("Y-m-d", strtotime("first day of next month")) . "<br>";
echo "이번 달 마지막 날: " . date("Y-m-d", strtotime("last day of this month")) . "<br>";
echo "1999년 12월 마지막 날: " . date("Y-m-d", strtotime("last day of December 1999")) . "<br>";
?>
시연화면
현재가아닌 특정 날짜 기준으로 계산 하고 싶을 때 사용
예제코드
<?php
// 기준 날짜: 2023년 2월 15일
$base_time = strtotime("2023-02-15");
// 2023년 2월 15일로부터 1달 뒤
$one_month_later = strtotime("+1 month", $base_time);
echo "기준 날짜: " . date("Y-m-d", $base_time) . "<br>";
echo "1달 뒤: " . date("Y-m-d", $one_month_later); // 결과: 2023-03-15
?>
시연화면
'PHP' 카테고리의 다른 글
[PHP] 상속(extends)을 사용하기 (0) | 2025.09.15 |
---|---|
[PHP] nullsafe 연산자 (?->): null 체크 지옥에서 벗어나기 (0) | 2025.09.12 |
[PHP] switch 문을 대체하는 match 표현식 (0) | 2025.09.05 |
[PHP] strpos(), strrpos()로 특정 문자의 위치 찾기 (1) | 2025.09.01 |
[PHP] 일반 배열보다 빠르고 메모리를 적게 쓰는 SplFixedArray (0) | 2025.08.31 |