import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DefaultChecks {
public static void main(String[] args) {
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
System.out.println("With Cal.."+dateFormatGmt.format(presentCal.getTime()));
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String currentDateTimeString = dateFormatGmt.format(new Date());
System.out.println("With format.."+currentDateTimeString);
}
}
输出:
With Cal..2014-11-14T12:50:23.400Z
With format..2014-11-14T07:20:23.400Z
最佳答案
日期是一个瞬间,并且您的 TimeZone
(s) 在两种格式调用之间是不同的。改成
SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); // <-- here
System.out.println("With Cal.."
+ dateFormatGmt.format(presentCal.getTime())); // <-- you use it
// here.
String currentDateTimeString = dateFormatGmt.format(new Date());
System.out.println("With format.." + currentDateTimeString);
我在这里得到了正确的输出。
关于java - 为什么将本地时间转换为 GMT 时会出现差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26924919/