mongo保存日期是一个64-bit整形数。java driver保存Date时会把他自动转换为标准时间GMT。如中国在GMT+8时区,保存2012-01-20 00:00:00到库中,查询后结果竟然是2012-01-19 16:00:00跟想要结果不一致。 可以在com.mongodb.util.JSON找到问题根源:
if (o instanceof Date) { Date d = (Date) o; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); serialize(new BasicDBObject("$date", format.format(d)), buf); return; }
所以我们的时间存进去就少了8小时。
下面用java代码写了一个获取写入mongo的时间方法:
/** * 计算得到MongoDB存储的日期,(默认情况下mongo中存储的是标准的时间,中国时间是东八区,存在mongo中少8小时,所以增加8小时) * http://www.iteye.com/problems/88507 * * @author: Gao Peng * @date: 2016年5月4日 上午9:26:23 * @param: @param * date * @param: @return * @return: Date */ public static Date getMongoDate(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar ca = Calendar.getInstance(); ca.setTime(date); ca.add(Calendar.HOUR_OF_DAY, 8); return String2Date(sdf.format(ca.getTime())); }