format.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // 서버·클라이언트 공용 순수 유틸. 'use client' 지시어 금지.
  2. export function formatDate(dateString: string|null): string {
  3. if (!dateString) {
  4. return '-';
  5. }
  6. const date = new Date(dateString);
  7. const now = new Date();
  8. const diffMs = now.getTime() - date.getTime();
  9. const diffSec = Math.floor(diffMs / 1000);
  10. const diffMin = Math.floor(diffSec / 60);
  11. const diffHour = Math.floor(diffMin / 60);
  12. const diffDay = Math.floor(diffHour / 24);
  13. const diffWeek = Math.floor(diffDay / 7);
  14. const diffMonth = Math.floor(diffDay / 30);
  15. const diffYear = Math.floor(diffDay / 365);
  16. if (diffSec < 60) return '방금 전';
  17. if (diffMin < 60) return `${diffMin}분 전`;
  18. if (diffHour < 24) return `${diffHour}시간 전`;
  19. if (diffDay < 7) return `${diffDay}일 전`;
  20. if (diffWeek < 5) return `${diffWeek}주 전`;
  21. if (diffMonth < 12) return `${diffMonth}개월 전`;
  22. return `${diffYear}년 전`;
  23. }
  24. export function getDateTime(dateString: string|null): string {
  25. if (!dateString) {
  26. return '-';
  27. }
  28. const date = new Date(dateString);
  29. return date.toLocaleString('ko-KR', {
  30. year: 'numeric',
  31. month: '2-digit',
  32. day: '2-digit',
  33. hour: '2-digit',
  34. minute: '2-digit',
  35. second: '2-digit',
  36. hour12: false
  37. }).replace(/\. /g, '.').replace(/\.(\d{2}:)/, ' $1');
  38. }
  39. export function isDateOverdue(dateString: string|null, days = 0): boolean {
  40. if (!dateString) {
  41. return false;
  42. }
  43. const limitDate = new Date(new Date(dateString));
  44. limitDate.setDate(limitDate.getDate() + days);
  45. return (new Date()) > limitDate;
  46. }
  47. /** Date → "yyyy.MM.dd HH:mm" (datetime-local 대체 입력 표시용) */
  48. export function formatDateInput(date: Date): string {
  49. const y = date.getFullYear();
  50. const m = String(date.getMonth() + 1).padStart(2, '0');
  51. const d = String(date.getDate()).padStart(2, '0');
  52. const h = String(date.getHours()).padStart(2, '0');
  53. const min = String(date.getMinutes()).padStart(2, '0');
  54. return `${y}.${m}.${d} ${h}:${min}`;
  55. }
  56. /** "yyyy.MM.dd HH:mm" → ISO string. 실패 시 빈 문자열 */
  57. export function parseDateInput(str: string): string {
  58. const match = str.match(/^(\d{4})\.(\d{2})\.(\d{2})\s+(\d{2}):(\d{2})$/);
  59. if (!match) {
  60. return '';
  61. }
  62. const [, y, m, d, h, min] = match;
  63. const date = new Date(+y, +m - 1, +d, +h, +min);
  64. if (isNaN(date.getTime())) {
  65. return '';
  66. }
  67. return date.toISOString();
  68. }