Yat*_*oel 17 java calendar date
我想知道当前的日期和时间.
代码
Calendar.getInstance();
Run Code Online (Sandbox Code Playgroud)
表示运行程序的系统的日期和时间,系统日期可能是错误的.
那么,无论运行程序的系统的日期和时间是什么,我都可以通过哪种方式获得正确的当前日期和时间?
the*_*Sin 41
在1.1之前的Java版本中,使用Date类是标准的:
Date now = new Date(); // Gets the current date and time
int year = now.getYear(); // Returns the # of years since 1900
Run Code Online (Sandbox Code Playgroud)
但是,在较新版本的Java中,大部分Date
类已被弃用(特别是getYear
方法).现在使用Calendar类更标准:
Calendar now = Calendar.getInstance(); // Gets the current date and time
int year = now.get(Calendar.YEAR); // The current year
Run Code Online (Sandbox Code Playgroud)
我完全不明白你的问题,但我可以回答你的标题:
GregorianCalendar gc = new GregorianCalendar(System.getCurrentTimeMillis());
int year = gc.get(Calendar.YEAR);
Run Code Online (Sandbox Code Playgroud)
如果您在互联网上,您也许可以询问已知且可信的时间源。如果运行你的程序的人想要阻止你的程序这样做(例如,如果你给了他们一个有时间限制的许可证,而他们不想支付更多的时间),他们可能会欺骗或阻止该连接。
在我参与的一个项目中,我们在硬件中放置了一个安全、可信的时间源,并且无法被篡改。它是为加密和许可而设计的,并有一个 Java 库来访问它。抱歉,我不记得设备的名称。
所以答案也许是,也许不是。