solr的date和java中的date之间的转换
在上篇中,我们通过调用了方法进行将本地的时间转换为solr的格式时间,我们在进行搜索传入时间参数的时候,必须是solr格式的时间,即: ,否则会有错误产生。
这里总结几种解决solr格式时间的方法:
1.通过日期类型的转换:
public static String getSolrDate(Date date) { SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss"); sdf2.setTimeZone(TimeZone.getTimeZone("UTC")); String result = sdf1.format(date) + "T" + sdf2.format(date) + "Z"; return result; }
2.使用日历格式进行修改:
参考:https://www.cnblogs.com/junrong624/p/6035185.html
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //Date d = format.parse(str.replace("Z", " UTC"));//注意是空格+UTC //System.out.println(d); Date date=new Date(); Calendar calendar=Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);//获得昨天时间 System.out.println(date); String temp=format.format(date); String hours=format.format(calendar.getTime()); System.out.println(temp); System.out.println(":::"+hours); int end=temp.indexOf("+"); String re=temp.substring(0,end)+"Z"; int end2=hours.indexOf("+"); String re2=hours.substring(0,end2)+"Z"; System.out.println("当前时间"+re); System.out.println("前一小时"+re2); try { System.out.println(format.parse(re.replace("Z", "UTC"))); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }
3.使用时间戳进行修改设置:
/**
* 获得时间减8
*/
public static Timestamp formatDateToTimestamp(Date dateTime){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar date2 = Calendar.getInstance(); date2.setTime(dateTime); date2.set(Calendar.HOUR, date2.get(Calendar.HOUR) - 8); Date endDate = null; try { endDate = sdf.parse(sdf.format(date2.getTime())); } catch (ParseException e) { e.printStackTrace(); } sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); String date=sdf.format(endDate); Timestamp stamp=Timestamp.valueOf(date); return stamp; }
4.修改源码
参考博客:
复写方法:
结果显示,日期格式未进行修改,但是时间没有相差8小时,原因是在solr加入的时候,它是以一种string类型存入,不会进行修改日期的时区,具体是还需要如何修改,后续完成后进行记录。