Java – 如何使当前日期独立于系统日期?

我想知道当前的日期和时间。

代码

Calendar.getInstance(); 

表示运行程序的系统的日期和时间,系统日期可能是错误的。

那么,无论运行程序的系统的日期和时间如何,我有什么方法可以获得正确的当前日期和时间吗?

如果您在互联网上,您可以提出已知且可信赖的时间来源。 如果运行程序的人想要阻止您的程序执行此操作(例如,如果您给他们一个时间限制的许可证并且他们不想支付更多时间),他们可能会欺骗或阻止该连接。

在我所参与的一个项目中,我们在硬件中放置了一个安全,可靠的时间源,无法被篡改。 它专为加密和许可而设计,并有一个Java库来访问它。 对不起,我记不起设备的名称了。

所以答案可能是肯定的,也许不是。

在1.1之前的Java版本中,使用Date类是标准的:

 Date now = new Date(); // Gets the current date and time int year = now.getYear(); // Returns the # of years since 1900 

但是,在较新版本的Java中,大多数Date类已被弃用(特别是getYear方法)。 现在使用Calendar类更标准:

 Calendar now = Calendar.getInstance(); // Gets the current date and time int year = now.get(Calendar.YEAR); // The current year 

我完全不明白你的问题,但我可以回答你的标题:

 GregorianCalendar gc = new GregorianCalendar(System.getCurrentTimeMillis()); int year = gc.get(Calendar.YEAR); 

您的系统可以访问Internet吗? 如果是这样,您可以使用具有精确时间服务的同步(例如: http : //tldp.org/HOWTO/TimePrecision-HOWTO/ntp.html )并授予您想要的权限。

编程级方法是为了从系统本身获取日期和时间而开发的。 除了指定的系统之外,您无法修改它们以获取日期。

对于您的其他要求,如果您希望真正拥有它,则需要在客户端计算机和服务器之间进行同步。

以下是从您选择的Web服务器获取HTTP格式(通常为UTC时区)的日期的一些代码。

当然,如果您无法控制物理硬件和操作系统,那么无法保证您能够与您要求的实际Web服务器通信……但无论如何。

 package some.package; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class Test { private static String getServerHttpDate(String serverUrl) throws IOException { URL url = new URL(serverUrl); URLConnection connection = url.openConnection(); Map> httpHeaders = connection.getHeaderFields(); for (Map.Entry> entry : httpHeaders.entrySet()) { String headerName = entry.getKey(); if (headerName != null && headerName.equalsIgnoreCase("date")) { return entry.getValue().get(0); } } return null; } public static void main(String[] args) throws IOException { String serverUrl = args.length > 0 ? args[0] : "https://google.com"; System.out.println(getServerHttpDate(serverUrl)); } }