프로그래밍/Back-end
[java] 현재 날짜로부터 n분전, n시간전, n일전, n주전, n달전 표기하기
꼬마봄이
2021. 6. 9. 23:38
알림 기능 구현을 사이드 프로젝트에서 담당하여 진행중에, 알람 표시 날짜를 n일전, n주전, n달전...으로 해달라는 요청을 받았다.
변경 전에는 그냥 알람창을 누르면 현재 날짜와 시간이 뜨도록 해뒀었다..
[구현 방법]
1. MySQL DB의 notice 테이블에 저장되어있는 noti_create 컬럼과 현재시간을 비교하여
현재 시간 - 알림 생성 시간 을 초(sec) 단위로 변환하기
2. 변환한 초를 분, 시, 일, 주, 달, 연도 로 표기하기
1️⃣[Controller]
final 상수를 선언하여 초, 분, 시, 일, 주, 달, 연도에 관련된 클래스와 비교 로직 클래스 생성한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
//알림 시간 설정(n일전, n주전, n달전, n년전)
private static class TIME_MAXIMUM {
public static final int SEC = 60;
public static final int MIN = 60;
public static final int HOUR = 24;
public static final int DAY = 7;
public static final int WEEK = 4;
public static final int MONTH = 12;
}
public static String formatTimeString(int diffTime) {
String msg = null;
if (diffTime < TIME_MAXIMUM.SEC) {
msg = "방금 전"; // sec
} else if ((diffTime /= TIME_MAXIMUM.SEC) < TIME_MAXIMUM.MIN) {
msg = diffTime + "분 전"; // min
} else if ((diffTime /= TIME_MAXIMUM.MIN) < TIME_MAXIMUM.HOUR) {
msg = (diffTime) + "시간 전"; // hour
} else if ((diffTime /= TIME_MAXIMUM.HOUR) < TIME_MAXIMUM.DAY) {
msg = (diffTime) + "일 전"; // day
} else if ((diffTime /= TIME_MAXIMUM.DAY) < TIME_MAXIMUM.WEEK) {
msg = (diffTime) + "주 전"; // week
} else if ((diffTime /= TIME_MAXIMUM.WEEK) < TIME_MAXIMUM.MONTH) {
msg = (diffTime) + "달 전"; // month
} else {
diffTime /= TIME_MAXIMUM.MONTH;
msg = (diffTime) + "년 전"; // year
}
return msg;
}
@RequestMapping(value = "/memberPush", method = RequestMethod.POST)
@ResponseBody
public HashMap <String, Object> memberPush(HttpSession session, Model model) throws Exception {
logger.info("memberPush");
HashMap<String, Object> result = new HashMap <String,Object>();
TogetherMemberVO vo = (TogetherMemberVO) session.getAttribute("member");
String memberEmail = vo.getM_email();
List<MemberNoticeVO> notice = memberNoticeService.notiList(memberEmail);
for(MemberNoticeVO notiVO : notice) { // 날짜 포맷 변경
notiVO.setNoti_time(formatTimeString(notiVO.getComparetime()));
}
if (notice.size() > 0) {
String size = "1";
result.put("size", size);
result.put("notice", notice);
}
return result;
}
|
cs |
알림 화면은 비동기식으로 띄우기 위해 AJAX를 이용했다!
여기서 사용한 Mapper.xml 의 쿼리는 다음과 같다.
2️⃣[Mapper.xml]
1
2
3
4
|
<select id="notiList" resultType="MemberNoticeVO">
SELECT *, TIMESTAMPDIFF(SECOND, NOTI_CREATE, NOW()) AS comparetime FROM MEMBER_NOTICE
WHERE m_email = #{m_email} order by noti_num DESC
</select>
|
cs |
MySQL의 TIMESTAMPDIFF 함수를 이용해서 초 단위의 차이를 가져왔다.
resultMap을 사용하기 번거로워서 VO에 comparetime 과 noti_time를 추가했다.. (이래도 되는거겠지?)
✨결과 화면✨
n일, n주, n달, n년 전까지 정상적으로 뜨는 것 확인 완료! :D