从 Mongo 中检索日期类型为字符串

Retrieve Date type as String from Mongo

数据 mongodb 保存在项目 collection 中,如下所示。

{name:item1, addedDate: 2021-03-04}

addedDate 保存为 Date 类型。 collection.

中有 1000 条这样的记录

我正在 java 中检索如下记录:

List<Item> itemList = new ArrayList<>();

@Autowired
MongoCollection<Item> itemCollection; 
  itemCollection.find().into(itemList);

商品pojo如下:

public class Item{
public String addedDate;

//Getters setters
}

无法获取和解析记录,因为 addedDate 是 String 类型。当我将其更改为 Date 类型时,它会起作用。我把它作为字符串保存在 pojo 中,因为作为回应我必须 return 它作为字符串。

我怎样才能做到这一点?请指教

您可以使用 LocalDate.

public class Item {
    private LocalDate addedDate;

    //public getters and setters
}

您可以从Trail: Date Time了解更多信息。