date-format-timezone.test.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { describe, expect, it } from "vitest";
  2. import { formatDate } from "@/lib/utils/date-format";
  3. describe("formatDate with timezone parameter", () => {
  4. // Fixed UTC timestamp: 2025-01-15T23:30:00Z
  5. const utcDate = new Date("2025-01-15T23:30:00Z");
  6. it("returns formatted date without timezone (original behaviour)", () => {
  7. const result = formatDate(utcDate, "yyyy-MM-dd", "en");
  8. // Without timezone, result depends on local TZ - just verify it returns a string
  9. expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/);
  10. });
  11. it("formats date in UTC timezone", () => {
  12. const result = formatDate(utcDate, "yyyy-MM-dd HH:mm", "en", "UTC");
  13. expect(result).toBe("2025-01-15 23:30");
  14. });
  15. it("formats date in Asia/Shanghai timezone (UTC+8)", () => {
  16. // 2025-01-15T23:30:00Z => 2025-01-16T07:30:00 in Asia/Shanghai
  17. const result = formatDate(utcDate, "yyyy-MM-dd HH:mm", "en", "Asia/Shanghai");
  18. expect(result).toBe("2025-01-16 07:30");
  19. });
  20. it("formats date in America/New_York timezone (UTC-5 in January)", () => {
  21. // 2025-01-15T23:30:00Z => 2025-01-15T18:30:00 in America/New_York (EST)
  22. const result = formatDate(utcDate, "yyyy-MM-dd HH:mm", "en", "America/New_York");
  23. expect(result).toBe("2025-01-15 18:30");
  24. });
  25. it("handles date-only format with timezone that crosses midnight", () => {
  26. // 2025-01-15T23:30:00Z is already 2025-01-16 in Asia/Shanghai
  27. const dateOnly = formatDate(utcDate, "yyyy-MM-dd", "en", "Asia/Shanghai");
  28. expect(dateOnly).toBe("2025-01-16");
  29. });
  30. it("preserves locale formatting with timezone", () => {
  31. const result = formatDate(utcDate, "PPP", "en", "UTC");
  32. // PPP in en locale: "January 15th, 2025"
  33. expect(result).toContain("January");
  34. expect(result).toContain("2025");
  35. });
  36. it("works with string date input and timezone", () => {
  37. const result = formatDate("2025-06-01T12:00:00Z", "yyyy-MM-dd HH:mm", "en", "Asia/Tokyo");
  38. // UTC 12:00 => JST 21:00
  39. expect(result).toBe("2025-06-01 21:00");
  40. });
  41. it("works with numeric timestamp and timezone", () => {
  42. const ts = utcDate.getTime();
  43. const result = formatDate(ts, "yyyy-MM-dd HH:mm", "en", "UTC");
  44. expect(result).toBe("2025-01-15 23:30");
  45. });
  46. it("falls back to local format when timezone is undefined", () => {
  47. const result = formatDate(utcDate, "yyyy-MM-dd", "en", undefined);
  48. expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/);
  49. });
  50. });