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?
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?
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):
America/New_York. 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:
Jump to Post— rproffitt 3,266If 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
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
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.