Java 往MongoDB 寫入時間和讀取時間

敘述

很多開發使用 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));

效果圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章