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

This is the code what we have written. We are getting an “Unparseable date error”. Can someone please help?

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate`, `OffsetDateTime` and/or `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 26 '20 at 19:08

2 Answers2

0

This is wrong:

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

The expression new Date().toString() does not return a string that conforms to the format yyyy-MM-DD, so if you try to parse it as if it is formatted that way, you will get an exception.

If you want a Date object that represents the current date and time, simply do this:

Date todaydate = new Date();

No need to convert the Date object to a string and trying to parse it.

If you need a string with the current date in the format yyyy-MM-dd then do this:

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

Note: You used DD in your date format string but you most likely meant dd. See the API documentation of SimpleDateFormat.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • Got it, but I need to convert the string into Mongo DB date format, 2020-05-26T14:34:27.664Z – Prasad Mayya M May 26 '20 at 14:29
  • 1
    That's ISO-8601 format. [Format it appropriately](https://stackoverflow.com/questions/3914404/how-to-get-current-moment-in-iso-8601-format-with-date-hour-and-minute/33532945). – Jesper May 26 '20 at 14:50
0

If you are trying to get the current date string in yyyy-MM-dd format. You can do format it like this

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormat.format(new Date());
vishnu
  • 1,961
  • 2
  • 7
  • 11