我想知道当前的日期和时间。
代码
Calendar.getInstance();
表示程序运行的系统日期和时间,系统日期可能不正确。
那么是否有任何方法可以获得正确的当前日期和时间,而不受程序所在系统的日期和时间的影响?
我想知道当前的日期和时间。
代码
Calendar.getInstance();
表示程序运行的系统日期和时间,系统日期可能不正确。
那么是否有任何方法可以获得正确的当前日期和时间,而不受程序所在系统的日期和时间的影响?
在Java 1.1之前的版本中,使用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);
您的系统是否可以接入互联网?如果可以,您可以使用与精确时间服务同步(例如:http://tldp.org/HOWTO/TimePrecision-HOWTO/ntp.html)并授予所需权限。
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<String, List<String>> httpHeaders = connection.getHeaderFields();
for (Map.Entry<String, List<String>> 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));
}
}
编程级别的方法是从系统本身获取日期和时间。您无法修改它们以获取除系统指定日期之外的日期。
对于您的额外要求,如果您真的需要它,您需要在客户端机器和服务器之间进行同步。