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
420 views
in Technique[技术] by (71.8m points)

javascript - 以用户的语言环境格式和时间偏移显示日期/时间(Display date/time in user's locale format and time offset)

I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.(我希望服务器始终在HTML中提供UTC日期,并在客户端站点上使用JavaScript将其转换为用户的本地时区。)

Bonus if I can output in the user's locale date format.(如果我可以用户的区域设置日期格式输出,则可以获得奖励。)

  ask by kch translate from so

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

1 Reply

0 votes
by (71.8m points)

Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.(似乎从UTC日期开始最简单的方法是创建一个新的Date对象并使用setUTC…方法将其设置为您想要的日期/时间。)

Then the various toLocale…String methods will provide localized output.(然后各种toLocale…String方法将提供本地化输出。)

Example:(例:)

 // This would come from the server. // Also, this whole block could probably be made into an mktime function. // All very bare here for quick grasping. d = new Date(); d.setUTCFullYear(2004); d.setUTCMonth(1); d.setUTCDate(29); d.setUTCHours(2); d.setUTCMinutes(45); d.setUTCSeconds(26); console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT) console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004 console.log(d.toLocaleDateString()); // -> 02/28/2004 console.log(d.toLocaleTimeString()); // -> 23:45:26 

Some references:(一些参考:)


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

...