敘述
很多開發使用 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));
效果圖: