我应该为我的 Javascript 使用 getHours() 还是 getUTCHours?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8024414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:01:22  来源:igfitidea点击:

Should I use getHours() or getUTCHours for my Javascript?

javascripthtml

提问by user950891

I want to get the time on the computer of the person who is accessing my website. Should I use getHours() or getUTCHours()?

我想在访问我网站的人的计算机上获得时间。我应该使用 getHours() 还是 getUTCHours()?

采纳答案by Adrian

Short answer is it depends. If you want the hours as it displays on a clock for their timezone you will want getHours() as it returns the hours in their local time. If you want the hours in Universal Time (no timezone adjustment) then use getUTCHours()

简短的回答是视情况而定。如果您想要在时钟上显示时区的小时数,您将需要 getHours() 因为它返回本地时间的小时数。如果您想要世界时的小时数(无时区调整),请使用 getUTCHours()

回答by Andrew Hare

I would recommend getUTCHours- keeping everything in UTC removes a lot of headaches when it comes to working with dates and times.

我建议getUTCHours- 在处理日期和时间时,将所有内容保留在 UTC 中可以消除很多麻烦。

回答by Niet the Dark Absol

It depends what you're using it for. If you want to get the user's local time, use getHours(). If you want to get something like a time offset (say, "hours until the new CoD is released in the UK"), use getUTCHours()as an absolute reference point. Bear in mind, however, that if the user's clock is set wrong, getUTC*()functions will return times that aren't really UTC - all they do really is remove the getGMTOffset()amount for you.

这取决于你用它做什么。如果要获取用户的本地时间,请使用getHours(). 如果您想获得诸如时间偏移之类的信息(例如“在英国发布新 CoD 之前的小时数”),请getUTCHours()用作绝对参考点。但是请记住,如果用户的时钟设置错误,getUTC*()函数将返回不是真正的 UTC 时间 - 它们所做的只是getGMTOffset()为您删除数量。

回答by mpen

getHourswill return the time according to their timezone, getUTCHourswill get their time converted to UTC. Would probably be easier to use getUTCHoursso everyone is returning their time in the same timezone.

getHours将根据他们的时区返回时间,getUTCHours将他们的时间转换为 UTC。可能会更容易使用,getUTCHours因此每个人都在同一时区返回他们的时间。

回答by Dany Khalife

It depends on what you want to do, but i'd agree with Andrew, if you use getUTC*** it becomes easier for you to handle dates and times

这取决于你想做什么,但我同意安德鲁,如果你使用 getUTC***,你可以更轻松地处理日期和时间