public static void main(String[] args) throws ParseException {
// 把mongodb日期转成yyyy-MM-dd HH:mm:ss日期
String date = "2024-08-27T15:59:40.327Z";
date = date.replace("Z", " UTC");//注意是空格+UTC
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
Date d = format.parse(date);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sf.format(d));
System.out.println(d);
// 把日期转成mongodb日期
String mongodate = format.format(sf.parse("2024-08-28 00:00:00"));
System.out.println(mongodate);
}
输出
2024-08-27 23:59:40
Tue Aug 27 23:59:40 CST 2024
2024-08-27T16:00:00.000 +0000
二、查询把mongodb日期转换
{
formattedDate: {
$dateToString: {
format: "%Y-%m-%d %H:%M:%S",
date: "$updateTime",
"timezone": "Asia/Shanghai"
}
}
}