|
2 | 2 |
|
3 | 3 | import shinhan.click.domain.chat.entity.Chat; |
4 | 4 |
|
| 5 | +import java.time.LocalDateTime; |
| 6 | +import java.time.format.DateTimeFormatter; |
| 7 | +import java.time.temporal.ChronoUnit; |
| 8 | +import java.util.Locale; |
| 9 | + |
5 | 10 | public record ChatPreview( |
6 | 11 | Long chatId, |
7 | 12 | String characterImageUrl, |
8 | 13 | String characterName, |
9 | 14 | String storyTitle, |
10 | | - String lastChat |
| 15 | + String lastChat, |
| 16 | + String timeAgo |
11 | 17 | ) { |
12 | 18 | public static ChatPreview from(Chat chat) { |
13 | 19 | return new ChatPreview( |
14 | 20 | chat.getId(), |
15 | 21 | chat.getCharacter().getCharacterImageUrl(), |
16 | 22 | chat.getCharacter().getName(), |
17 | 23 | chat.getCharacter().getStory().getTitle(), |
18 | | - chat.getMessages().get(chat.getMessages().size() - 1).getContent() |
| 24 | + chat.getMessages().get(chat.getMessages().size() - 1).getContent(), |
| 25 | + getTimeAgo(chat.getMessages().get(chat.getMessages().size() - 1).getCreatedAt()) |
19 | 26 | ); |
20 | 27 | } |
| 28 | + |
| 29 | + private static String getTimeAgo(LocalDateTime createdAt) { |
| 30 | + LocalDateTime now = LocalDateTime.now(); |
| 31 | + long days = ChronoUnit.DAYS.between(createdAt.toLocalDate(), now.toLocalDate()); |
| 32 | + |
| 33 | + if (days == 0) { |
| 34 | + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("a h:mm") |
| 35 | + .withLocale(Locale.KOREA); |
| 36 | + return createdAt.format(formatter); |
| 37 | + } else if (days == 1) { |
| 38 | + return "1일 전"; |
| 39 | + } else if (days < 30) { |
| 40 | + return days + "일 전"; |
| 41 | + } else if (days < 365) { |
| 42 | + long months = days / 30; |
| 43 | + return months + "개월 전"; |
| 44 | + } else { |
| 45 | + long years = days / 365; |
| 46 | + return years + "년 전"; |
| 47 | + } |
| 48 | + } |
| 49 | + |
21 | 50 | } |
0 commit comments