I have a unix timestamp for each cooment in my database. I want to output the user date and time depending on their location, or timezone.

How do I do that properly?

Dani AI

Generated

Store all timestamps in UTC (Unix epoch or UTC DATETIME) and convert to the viewer’s timezone at render time. That removes ambiguity, keeps the DB simple, and makes conversions predictable across DST changes.

Detection strategy (recommended precedence):

  1. Explicit user preference saved in the profile (as @rproffitt suggested) — store an IANA timezone name like America/New_York.
  2. Browser-detected timezone (use the browser’s Intl API to get an IANA name, then persist it to the profile or a cookie on first visit). This reflects the device clock and is not affected by VPN-based IP location.
  3. IP geolocation only as a last resort — it’s unreliable with VPNs, Tor and some mobile carriers and raises privacy considerations.

Example PHP conversion (assumes the DB timestamp is UTC and the user tz is an IANA name):

$ts = 1536400000;               // UTC unix timestamp from DB
$userTz = 'America/Los_Angeles';// IANA timezone from profile or client

$utc = new DateTimeImmutable('@' . $ts); // creates UTC time
$local = $utc->setTimezone(new DateTimeZone($userTz));
echo $local->format('Y-m-d H:i:s');      // formatted in user's timezone

Notes and troubleshooting:

  • Always store the source of the timezone (profile, browser, IP) for debugging.
  • Store IANA names, not numeric offsets — offsets don’t handle DST. PHP’s DateTime/DateTimeZone will apply DST rules automatically when given an IANA zone.
  • Keep server tzdata up to date and fall back to UTC when no reliable timezone is available.
  • For docs and authoritative details see the PHP DateTime/DateTimeZone manual, the browser Intl API docs, and the IANA time zone database: PHP DateTime, PHP DateTimeZone, MDN Intl DateTimeFormat.resolvedOptions, IANA time zones.

Recommended Answers

All 3 Replies

Think about how users get to the Internet today. You can't count on their location being accurate since they could be using a VPN, Tor or another system. Fix? Just add their timezone to their user profile.

Yes, but I want to get their timezone even if they were using a VPN, or whatever. Is there an effeciant way?

If they are using a VPN you usually get the TZ of where they appear according to the VPN. There's nothing wrong about that which is why my view is to let them set the TZ in their profile.

But if you insist, then use this call: Intl.DateTimeFormat().resolvedOptions().timeZone

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.