처음부터 차근차근

date를 '~일 전', '~ 분 전' 으로 나타내는 방법 본문

프로그래밍/PHP

date를 '~일 전', '~ 분 전' 으로 나타내는 방법

_soyoung 2022. 2. 19. 16:30
반응형

웹 페이지를 둘러보면 작성 날짜를 '2022-01-01' 이런식으로 나타내지 않고 '몇 분 전', '몇 일 전' 이렇게 나타내는것을 볼 수 있다.

출처 : 번개장터

 

 

구현 코드

감사하게도 어떤 분이 미리 만들어 놓으신 코드가 있어서 가져와서 사용했다.

함수의 매개변수로는 '2022-01-01' 형식의 String을 넣으면 된다.

public function get_date($datetime){
    $time_lag = time() - strtotime($datetime);
	
    if($time_lag < 60) {
        $posting_time = "방금";
    } elseif($time_lag >= 60 and $time_lag < 3600) {
        $posting_time = floor($time_lag/60)."분 전";
    } elseif($time_lag >= 3600 and $time_lag < 86400) {
        $posting_time = floor($time_lag/3600)."시간 전";
    } elseif($time_lag >= 86400 and $time_lag < 2419200) {
        $posting_time = floor($time_lag/86400)."일 전";
    } elseif($time_lag >= 2592000 and $time_lag < 31104000) {
        $posting_time = floor($time_lag/2592000)."개월 전";
    } elseif($time_lag >= 31104000 and $time_lag < 31536000) { 
        $posting_time = "1년 전";
    } else {
        $posting_time = floor($time_lag/31536000)."년 전";
    }

    return $posting_time;
}

 

 

 

 

코드 출처 : https://sir.kr/g5_tip/1981

반응형

'프로그래밍 > PHP' 카테고리의 다른 글

date time을 오전 00:00, 오후 00:00로 나타내기  (0) 2022.06.06
PHP 보안  (0) 2021.10.05
PHP 기본 정리 2  (0) 2021.10.04
PHP 기본 정리  (0) 2021.10.03
PHP의 원리  (0) 2021.10.02
Comments