如何使用 PHP 或 javascript 在与用户相同的时区显示日期时间? [英] How do I show datetime in the same time zone as user using PHP or javascript?

查看:18
本文介绍了如何使用 PHP 或 javascript 在与用户相同的时区显示日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设现在我有日期时间显示如下:

Suppose now I've got the datetime to show like this:

2010-05-29 15:32:35

可以通过date_default_timezone_get获取对应的时区,

The the corresponding time zone can be get by date_default_timezone_get,

如何在与用户浏览器相同的时区输出结果,以免用户混淆?

how do I output the result in the same time zone as user's browser so that users don't get confused?

推荐答案

没有可靠的方法可以从 PHP 或 JavaScript 读取用户的区域设置时区设置.

There is no reliable way to read the user's locale timezone settings from PHP or JavaScript.

在 JavaScript 中,您可以读取 UTC 与用户当前时区时间之间的偏移量,但这不会为您提供时区名称,因此您要么关闭时区标识符(使时间完全不明确)或者包含它是一个像 UTC+01:00 这样的显式偏移量,这很丑陋,而且仍然不考虑在不同 DST 期间更改时区.

In JavaScript you can read the offset between UTC and the time in the user's current timezone, but that doesn't give you a timezone name, so you're left either leaving the timezone identifier off (making the times completely ambiguous) or including it is an explicit offset like UTC+01:00, which is ugly, and still doesn't take care of changing timezones over different DST periods.

正如 bobah 所说,您可以在 JavaScript Date 上使用 toLocaleString() 以在客户端的真实桌面时区输出它.但是,通过这种方式,您根本无法控制日期格式.例如,在我的机器上,Chrome 输出笨拙:

As bobah says, you can use toLocaleString() on a JavaScript Date to output it in the client's real desktop timezone. However, this way you get no control at all over the date formatting. For example on my machine Chrome outputs the unwieldy:

Sat May 29 2010 15:03:46 GMT+0200 (W. Europe Daylight Time)

而 Opera 只是咳嗽:

Whereas Opera just coughs up:

29/05/2010 15:03:46

因为它根本没有说明时区,所以模棱两可是无用的.IE 同样简洁,Safari 也没有声明时区.Firefox 在 Linux 上对我有用,但在 Windows 上不行.啊.

Which, as it doesn't state the timezone at all, is uselessly ambiguous. IE is similarly terse, and Safari states no timezone either. Firefox does for me on Linux, but not on Windows. Argh.

因此,如果您需要可靠性,处理时区的唯一方法是让用户在其站点设置中手动选择一个,然后在为他们生成页面时从 UTC 转换为该时区.您可以在 JavaScript 中猜测最有可能的一些常见时区可能是哪个(请参阅 这个问题 策略),但你不能保证你是对的.

So if you need reliability the only way to handle timezones is to let the user manually choose one in their site settings, then convert from UTC to that timezone when you're producing a page for them. You can make a guess in JavaScript as to which the most likely of some common timezones it might be (see this question for strategies), but you can't guarantee you'll be right.

这篇关于如何使用 PHP 或 javascript 在与用户相同的时区显示日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆