我在 js 中执行以下操作来获取时间字符串:
(new Date()).toTimeString().substring(0, 8)
我所需要的只是这个字符串(绝对不需要像 moment.js 这样的东西)。当谷歌搜索时没有看到有人这样做。我在这里所做的事情是否有任何严重的缺点\可能的问题?
最佳答案
toTimeString
method的返回值在 ECMAScript 5 中指定:
The contents of the String are implementation-dependent, but are intended to represent the “time” portion of the Date in the current time zone in a convenient, human-readable form.
浏览器或环境可能会合法地生成一种会破坏您的方法的格式,因为 toTimeString
的结果完全依赖于实现。例如,不使用前导零,或省略秒,或使用 AM/PM 代替 24 小时时间等。
我不知道是否所有环境都使用相同的格式,但我假设大多数环境都选择 ISO 8601 格式,因为还有其他指定的函数(例如 toISOString
)无论如何都需要 ISO 格式。就错误责任而言,在极少数情况下,出现某些环境不适用于您的代码时,我会说您的代码将因依赖非标准行为而出现错误。
相比之下,toISOstring
的返回值为standardized as YYYY-MM-DDTHH:mm:ss.sssZ
(这始终是文字 T
,如果是 UTC,则为文字 Z
),但它可能对您没有帮助,因为它始终使用 UTC 时区,而不是本地环境时间。
关于javascript - 获取 HH :MM:SS time string in javascript 的一种黑客方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26238738/