Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

javascript - 使用设置的时区创建日期而不使用字符串表示形式(Create a Date with a set timezone without using a string representation)

I have a web page with three dropdowns for day, month and year.(我有一个网页,其中有三个下拉菜单,分别是日,月和年。)

If I use the JavaScript Date constructor that takes numbers, then I get a Date object for my current timezone:(如果我使用带数字的JavaScript Date构造函数,则将获得当前时区的Date对象:) new Date(xiYear, xiMonth, xiDate) Give the correct date, but it thinks that date is GMT+01:00 due to daylight savings time.(输入正确的日期,但由于夏令时,它认为该日期为GMT + 01:00。) The problem here is that I then pass this Date to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one.(这里的问题是,我随后将此Date传递给Ajax方法,并且在服务器上反序列化该日期时,该日期已转换为GMT,因此浪费了一个小时,从而使这一天倒退了一个小时。) Now I could just pass the day, month, and year individually into the Ajax method, but it seems that there ought to be a better way.(现在,我可以将日期,月份和年份分别传递给Ajax方法,但是似乎应该有一个更好的方法。) The accepted answer pointed me in the right direction, however just using setUTCHours() by itself changed:(可接受的答案为我指明了正确的方向,但是仅使用setUTCHours()本身就发生了变化:) Apr 5th 00:00 GMT+01:00 to(至) Apr 4th 23:00 GMT+01:00 I then also had to set the UTC date, month and year to end up with(然后,我还必须设置UTC日期,月份和年份,最后以) Apr 5th 01:00 GMT+01:00 which is what I wanted.(这就是我想要的。)   ask by Dan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.(使用.setUTCHours() ,可以在UTC时间中实际设置日期,这将使您可以在整个系统中使用UTC时间。)

You cannot set it using UTC in the constructor though, unless you specify a date-string. ( 但是,除非指定日期字符串,否则不能在构造函数中使用UTC进行设置。 ) Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.(使用new Date(Date.UTC(year, month, day, hour, minute, second)) ,可以从特定的UTC时间创建日期对象。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...