叙述
很多开发使用 Java 往MongoDB 写入时间和读取时间,都会遇到时间不匹配或者格式不对的情况。
现在给出标准代码,方便大家开发。
解决方案
这些代码都是从现有程序中扣出来的部分,只供参考。
写入时间
/*获取MongoDB的当前时间,时区UTC转GMT*/
public static Date getMongoDBDate() {
Calendar calle = Calendar.getInstance();
calle.setTime(new Date());
calle.add(Calendar.HOUR_OF_DAY, +8);
return calle.getTime();
}
效果图:
读取时间
Document doc = collection.find().first();
Date date = doc.getDate("date");
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
formattedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(formattedDate.format(date));
效果图: