Simple Date and Time Functions You’ll Use Every Day
1. Getting the current date and time
- Use a built-in function to get “now” in your environment (e.g., Date() in JavaScript, datetime.now() in Python).
- Use UTC versions (e.g., Date.now()/toUTCString(), datetime.utcnow()) when you need timezone-independent values.
2. Formatting dates for display
- Convert a date object to a human-friendly string (locale-sensitive or fixed).
- Use libraries or Intl APIs for robust formatting (e.g., Intl.DateTimeFormat in JS, strftime in many languages).
- Common patterns: YYYY-MM-DD, MM/DD/YYYY, DD MMM YYYY, and ISO 8601 for interchange.
3. Parsing dates from strings
- Parse user input or external data into date objects. Prefer strict/explicit formats (ISO 8601) to avoid ambiguity.
- Validate parsed dates to catch invalid or out-of-range values.
4. Timezone handling
- Store and transfer timestamps in UTC. Convert to local time only for display.
- Be explicit about timezone offsets when parsing or formatting. Use timezone-aware libraries (e.g., luxon, date-fns-tz, pytz/zoneinfo).
5. Adding/subtracting intervals
- Use dedicated functions to add days, months, or years rather than manipulating numeric timestamps directly to avoid calendar edge cases (month length, DST).
- Handle daylight saving changes by using timezone-aware arithmetic when necessary.
6. Comparing dates and durations
- Compare timestamps (milliseconds/seconds since epoch) for exact ordering.
- Use duration objects or functions to compute differences and express them in human units (hours, days).
7. Working with ISO 8601
- Prefer ISO 8601 (e.g., 2026-03-06T14:30:00Z) for APIs and storage—it’s unambiguous and widely supported.
8. Displaying relative times
- Show “2 hours ago” or “in 5 days” using relative-time utilities or Intl.RelativeTimeFormat for better UX.
9. Validation and edge cases
- Validate inputs (leap years, invalid dates like Feb 30).
- Account for locale differences in week start, date ordering, and numbering.
10. Use libraries for complexity
- For production systems, prefer well-maintained libraries (e.g., date-fns, luxon, moment-timezone retired but still used, Python’s dateutil) to avoid subtle bugs.
Practical tip: store everything in UTC (ISO 8601) and only convert to local/timezone-aware formats when presenting to users.