用Java确定另一个国家的互联网时间
我正在开发一个将被世界各地的人们使用的Java应用程序。 一项function要求它显示澳大利亚墨尔本当前时间。
我找到了这个答案,并按如下方式调整了代码,但它返回了我当前的时间(如预期的那样)。 它使用Apache Commons Net库 :
try { String TIME_SERVER = "time-a.nist.gov"; NTPUDPClient timeClient = new NTPUDPClient(); InetAddress inetAddress = InetAddress.getByName(TIME_SERVER); TimeInfo timeInfo = timeClient.getTime(inetAddress); long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); return new Date(returnTime); } catch (Exception e) { System.out.println(e.getMessage()); return null; }
如何修改此代码以返回墨尔本的时间,而不是我的时间? 我也愿意接受其他解决方案来解决这个问题。
谢谢!
编辑:
根据Jon的建议,我使用了JodaTime库并构建了以下代码来解决问题。 通过将Australia / Melbourne更改为此处找到的任何时区,它可以用于其他时区。
try { //Get the time for the current time zone. String TIME_SERVER = "time-a.nist.gov"; NTPUDPClient timeClient = new NTPUDPClient(); InetAddress inetAddress = InetAddress.getByName(TIME_SERVER); TimeInfo timeInfo = timeClient.getTime(inetAddress); long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); //Format it to the Melbourne TimeZone. DateTimeZone tzMelbourne = DateTimeZone.forID("Australia/Melbourne"); return new DateTime(returnTime).toDateTime(tzMelbourne); } catch (Exception e) { System.out.println(e.getMessage()); return null; }
您当前正在返回一个没有时区的java.util.Date
。 这只是一个瞬间。 它不在您的时区或其他时区 – 它只是一瞬间。 当您调用toString()
时,它将为您提供本地时区的文本表示,但这不是对象中数据的一部分。
如果您需要表示“特定时区的日期/时间”,那么您应该使用Calendar
类,或者理想地使用Joda Time ,这是一个更好的日期/时间API。
或者,如果您只是尝试格式化特定时区中的日期/时间,则可以使用SimpleDateFormat
– 设置时区,然后设置您已经返回的Date
值的格式。
您可以使用java.util.TimeZone
来获取世界上特定地点的时间,而不是从NTP服务器查找。(它也知道节省日光)您的时区ID是“澳大利亚/墨尔本”。
TimeZone australiaMelbourneTimeZone = TimeZone.getTimeZone("Australia/Melbourne"); Calendar dateTime = Calendar.getInstance(tz); //Use this Calendar instance to print time
不是:我通过转储java.util.TimeZone支持的所有可用时区ID,找到了Timezone ID Australia/Melbourne
,如下所示:
for(String timeZoneID: TimeZone.getAvailableIDs()) { System.out.println(timeZoneID); }
输出包括“澳大利亚/墨尔本”如下:
…澳大利亚/布里斯class澳大利亚/堪培拉澳大利亚/ Currie澳大利亚/霍巴特澳大利亚/ Lindeman 澳大利亚/墨尔本澳大利亚/新南威尔士州澳大利亚/昆士兰澳大利亚/悉尼澳大利亚
检查一下 。 您可以获取日历实例并更改其时区。
- Apache Commons HttpClient是否支持GZIP?
- 为什么我用Apache Commons FileUpload获得“FileUploadException:Stream意外结束”?
- 在Java中通过FTP创建文件夹层次结构
- 使用Apache Commons FTPClient监控进度
- 使用commons或Javascript比较两个文件
- 根据Java中的元素属性将列表拆分为多个子列表
- html多部分表单中输入文本字段的值
- 可以将apache FileUtils.writeLines()附加到文件(如果存在)
- 文件上传“multipart / form”exceptionorg.apache.commons.fileupload.FileUploadBase $ InvalidContentTypeException