1.mongoDB条件表达式
2.MongoDB中的日期格式 是 UTC 通用标准,格式为"yyyy-MM-dd HH:mm:ss.000'Z'"。
该时间比中国北京时间晚了8个小时,即·ISODate("2018-09-13T14:04:05.268Z")相当于北京时间2018-09-13 06:04:05.268
因为mongo中的Date类型以UTC(Coordinated Universal Time)存储,就等于GMT(格林尼治标准时)时间。而系统时间使用的是GMT+0800时间,两者正好相差8个小时。
import lombok.extern.slf4j.Slf4j; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 时间格式转换工具类 */ @Slf4j public class DateUtils { public final static String PATTERN_YYYYMMDDHHMM = "yyyyMMddHHmm"; public final static String PATTERN_YYYYMMDD = "yyyyMMdd"; public static int dateDiffMinutes(Date start, Date end) { long diff = end.getTime() - start.getTime(); return (int) (diff / 1000 / 60); } public static String formatDate(Date date, String pattern) { if (date == null) { throw new IllegalArgumentException("date is null"); } else if (pattern == null) { throw new IllegalArgumentException("pattern is null"); } else { SimpleDateFormat formatter = new SimpleDateFormat(pattern); return formatter.format(date); } } /** * mongo 日期查询isodate * * @param dateStr * @return */ public static Date dateToISODate(Date dateStr) { //T代表后面跟着时间,Z代表UTC统一时间 Date parse = null; try { // 解析字符串时间 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); parse = format.parse(format.format(dateStr)); } catch (ParseException e) { log.error("format time to ISODate is err,the param={}, e={}", dateStr, e.getMessage()); ResponseUtil.throwBusinessException("时间格式转换为ISODate失败!"); } return parse; } }
3.案例
DBObject dbObject = new BasicDBObject(); dbObject.put("updateTime", BasicDBObjectBuilder.start("$gte", DateUtils.dateToISODate(new Date(updateTime))) .add("$lte", DateUtils.dateToISODate(new Date())).get()); Query query = new BasicQuery(dbObject); List<UserConnectInfo> userConnectInfos = mongoTemplate.find(query, UserConnectInfo.class, USER_INFO_COLLECTION_NAME);