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);
