Skip to content

Commit

Permalink
getParsedDate - add 8h to account for timezone
Browse files Browse the repository at this point in the history
  • Loading branch information
adriangohjw committed Dec 27, 2024
1 parent 0450936 commit 19c7eec
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
6 changes: 3 additions & 3 deletions packages/components/src/utils/__tests__/getParsedData.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ describe("getParsedDate", () => {
expect(result).toStrictEqual(new Date(2023, 5, 15))
})

it("parses ISO 8601 format correctly", () => {
const result = getParsedDate("2023-07-20T14:30:45.123Z")
expect(result).toStrictEqual(new Date(2023, 6, 20, 14, 30, 45, 123))
it("parses ISO 8601 format correctly in Singapore timezone", () => {
const result = getParsedDate("2023-07-20T16:00:00.000Z")
expect(result).toStrictEqual(new Date(2023, 6, 21, 0, 0, 0, 0))
})

it("returns current date for unsupported format", () => {
Expand Down
12 changes: 10 additions & 2 deletions packages/components/src/utils/getParsedDate.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { isMatch, parse } from "date-fns"

const TIMEZONE_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
const SUPPORTED_DATE_FORMATS = [
"dd/MM/yyyy",
"d MMM yyyy",
"d MMMM yyyy",
"dd MMM yyyy",
"dd MMMM yyyy",
"yyyy-MM-dd",
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
TIMEZONE_DATE_FORMAT,
]

export const getParsedDate = (dateString: string) => {
Expand All @@ -20,7 +21,14 @@ export const getParsedDate = (dateString: string) => {

try {
if (isMatch(dateString, format)) {
return parse(dateString, format, new Date())
let offsetDate = dateString
if (format === TIMEZONE_DATE_FORMAT) {
offsetDate = new Date(
// Add 8 hours to account for the Singapore timezone offset
new Date(dateString).getTime() + 8 * 60 * 60 * 1000,
).toISOString()
}
return parse(offsetDate, format, new Date())
}
} catch (e) {
return new Date()
Expand Down

0 comments on commit 19c7eec

Please sign in to comment.