Rules Hub
Coding Rules Library
Abstract date parsing logic into utilities
Avoid manually parsing date strings with `new Date()` or `split()` due to timezone ambiguity and fragility. Use centralized utilities instead.
Bad example
| 1 | function IssueDate({ dateString }: { dateString: string }) { |
| 2 | // Bad: '2023-10-10' is parsed as UTC midnight, which may display as |
| 3 | // the previous day in western timezones (e.g., Oct 9th). |
| 4 | const date = new Date(dateString); |
| 5 |
|
| 6 | // Bad: Manual splitting is verbose and breaks if the format changes. |
| 7 | const [year, month, day] = dateString.split('-'); |
| 8 |
|
| 9 | return <span>{date.toLocaleDateString()}</span>; |
| 10 | } |
Explanation (EN)
Using `new Date(string)` on purely date strings (YYYY-MM-DD) creates timezone ambiguity (UTC vs Local), often leading to off-by-one errors. Manual string splitting is brittle and verbose.
Objašnjenje (HR)
Korištenje `new Date(string)` na datumskim stringovima (YYYY-MM-DD) stvara nejasnoće oko vremenskih zona (UTC vs lokalno), što često dovodi do grešaka u datumu. Ručno dijeljenje stringova je nestabilno i opširno.
Good example
| 1 | import { parseDate, formatDate } from '@/utils/date'; |
| 2 |
|
| 3 | function IssueDate({ dateString }: { dateString: string }) { |
| 4 | // Good: The utility handles parsing consistency (e.g. treating as local or UTC). |
| 5 | const label = formatDate(dateString, 'dd.MM.yyyy'); |
| 6 |
|
| 7 | return <span>{label}</span>; |
| 8 | } |
Explanation (EN)
A centralized utility function ensures deterministic parsing and formatting across the application, abstracting away browser inconsistencies and timezone logic.
Objašnjenje (HR)
Centralizirana uslužna funkcija osigurava determinističko parsiranje i formatiranje kroz cijelu aplikaciju, apstrahirajući nekonzistentnosti preglednika i logiku vremenskih zona.
Notes (EN)
Libraries like `date-fns` or `dayjs` are recommended over native `Date` manipulation for complex logic.
Bilješke (HR)
Preporučuje se korištenje biblioteka poput `date-fns` ili `dayjs` umjesto native `Date` manipulacije za složeniju logiku.