How Computers Store and Manage Time

Hai To (Hector)Hai To (Hector)
1 min read

How Do Computers Store Time?

  • Unix Time (Epoch Time)

  • System Time

  • File System Timestamps

  • Network Time Protocol (NTP)

  • Binary-Coded Decimal (BCD)

  • System BIOS/UEFI Time

Unix Time (Epoch Time)

UNIX timestamp: the number of seconds that have elapsed since 1970-01-01 at 00:00:00 UTC

  • Example:

    • Timestamp in seconds: 1695718262

    • Timestamp in milliseconds: 1695718262342

  • Facts:

    • In older 32bit systems, the signed integer will overflow in 2038

    • Why 1970? The Unix OS was created in the late 1960s and early 1970s. Unix engineers arbitrarily selected 1970

Datetime Format

  • ISO 8601: 2023‐09‐25T16:20:52+07:00, 2023‐09‐25T09:20:52Z

    • Z = +00:00
  • Vietnam: 26/09/2023

  • RFC 2822: Mon, 25 Sep 2023 09:16:58 +0000

  • Javascript: YYYY-MM-DDTHH:mm:ss.sssZ

  • Java: Tue Sep 26 16:05:37 ICT 2023 (+0700)

  • RFC 3339

When to use DateTime, Timestamp?

  • Timestamp: to record a (more or less) fixed point in time.

    • Example: created_at
  • Datetime: time can be set and changed arbitrarily.

    • Example: schedule time for appointments

Best Practices

Backend uses UTC time zone + ISO 8601/timestamp

Frontend uses local datetime (show timezone)

DB stores as timestamp if possible

Store datetime with time zone

MySQL: use fractional seconds for accuracy

JVM timezone != OS timezone

Be careful with:

  • Time zone

  • Datetime format

  • Fractional Seconds

1
Subscribe to my newsletter

Read articles from Hai To (Hector) directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hai To (Hector)
Hai To (Hector)