在应用 TimeZone“Europe/Warsaw”后,我使用以下函数以秒为单位获取时间。
我正确获取日期,但是一旦我以秒为单位转换日期,我的输出就会出错。服务器期望时区“欧洲/华沙”中的秒数。摆脱这种困境的最佳方法是什么?
public static long getTimeInSeconds() {
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
//Will get in Warsaw time zone
String date = sdf.format(calendar.getTime());
Date date1 = sdf.parse(date);
//Convert time in seconds as required by server.
return (date1.getTime() / 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)