【问题标题】:Unparseable date error format in Spring Boot Mongo DBSpring Boot Mongodb中无法解析的日期错误格式
【发布时间】:2020-09-13 07:07:36
【问题描述】:
MongoCollection<Document> Profile_List = db.getCollection("Profile_List");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD"); 
Date todaydate = format.parse(new Date().toString()); 
ArrayList<Document> activeList=profile.find(Filters.regex("lastActive",todayDate.toString())).into(new ArrayList<Document>());

这是我们编写的代码。我们收到“无法解析的日期错误”。有人可以帮忙吗?

【问题讨论】:

  • 我建议你不要使用SimpleDateFormatDate。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateOffsetDateTime 和/或Instant

标签: mongodb spring-boot


【解决方案1】:

这是错误的:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());

表达式new Date().toString() 不返回符合yyyy-MM-DD 格式的字符串,因此如果您尝试将其解析为该格式,则会出现异常。

如果您想要一个代表当前日期和时间的Date 对象,只需执行以下操作:

Date todaydate = new Date();

无需将Date 对象转换为字符串并尝试解析它。

如果您需要格式为yyyy-MM-dd 的当前日期字符串,请执行以下操作:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String todaydate = format.format(new Date());

注意:您在日期格式字符串中使用了DD,但您的意思很可能是dd。请参阅API documentation of SimpleDateFormat

【讨论】:

  • 知道了,但我需要将字符串转换为Mongo DB日期格式,2020-05-26T14:34:27.664Z
  • 这是 ISO-8601 格式。 Format it appropriately.
【解决方案2】:

如果您试图以yyyy-MM-dd 格式获取当前日期字符串。你可以像这样格式化它

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormat.format(new Date());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多