问题描述
我想在本地cloudant查询中将数据按标准日期排序.我的数据库文档中有insert_ts.我的简单查询代码是:-
i want to sort my data as par desc date in local cloudant query.i have insert_ts in my database document.my code for simple query is:-
public List<BasicDocumentMAP> allTasksWithAllArg(Map<String, Object> query, int skip, int limit, List<String> fields, List<Map<String, String>> sortDocument) {
int nDocs = this.sunDatastore.getDocumentCount();
QueryResult all = this.im.find(query, skip, limit, fields, sortDocument);
List<BasicDocumentMAP> arrayListBasicDocumentMAP = new ArrayList<>();
// Filter all documents down to those of type Task.
for (DocumentRevision rev : all) {
}}
请帮助我按日期对数据进行排序.谢谢
please help me to sort data as date wise. thank you
推荐答案
更新:原始答案(位于底部)显示如何按年份排序(OP询问如何获取年份,所以我认为那是他们想要的排序方式).这是按日期排序的方法:
Update: The original answer (at the bottom) shows you how to sort by year (OP asked how to get the year, so I assumed that was how they wanted to sort). This is how to sort by date:
将insert_ts
字段更改为日期,或添加一个新的日期字段,例如:
Either change the insert_ts
field to be a date, or add a new field that is a date, for example:
Date insertTsDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
insertTsDate = dateFormat.parse(insert_ts);
}
catch (Exception e) {
// handle exception
}
然后在文档中添加一个名为insert_ts_date
(或任何您想调用的名称)的新字段,将其设置为上面的insertTsDate
变量,并按如下方式进行排序:
Then add a new field to your document called insert_ts_date
(or whatever you want to call it), set it to the insertTsDate
variable above, and sort like so:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByInsertTsDate = new HashMap<String, String>();
sortByInsertTsDate.put("insert_ts_date", "asc");
sortDocument.add(sortByInsertTsDate);
原始答案:
我认为您将不得不在文档中明确添加Year属性.如果您有年份,则只需将其添加到文档中即可.如果您需要从字符串中解析它,则可以使用regex或Date/Calendar类来解析日期:
I think you are going to have to explicitly add a year property to your document. If you have the year then just add it to your document. If you need to parse it from the string you can use regex or the Date/Calendar classes to parse the date:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
Date date = dateFormat.parse(insert_ts);
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
}
catch (Exception e) {
// handle exception
}
然后按以下方式发出查询:
Then issue your query as follows:
List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByYear = new HashMap<String, String>();
sortByYear.put("year", "asc");
sortDocument.add(sortByYear);
这篇关于如何在Cloudant查询中对日期进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!