我的对象的字段为timestamp
,类型为java.sql.Timestamp;
。
而且我需要从集合中获取具有昨天日期的对象。
怎么弄他们?
我的意思是我需要这样的东西
for(int i = 0; i < items.size(); i++) {
(if the items.get(i).date == yesterday_date)
(get object)
}
答案 0 :(得分:2)
您可以按照 Jiger Joshi 的方法Answered获取昨天Date
。
使用new Timestamp(java.util.Date)
即可获得昨天的时间戳,您应该使用Timestamp#equals
来等待两个不同的时间戳。
if (items.get(i).date.equals(getYesterdaytimestamp())){
...
}
在实施此功能时,您必须考虑一些事项。返回Calender#getTime
对象和日期对象的Date
包含日期和时间,因此在这种情况下,您的等效日期或时间戳必须与昨天的日期和时间完全相等。
如果要求是,它需要等于昨天不等于时间不是很重要的事实。在这种情况下,您需要在丢弃时间部分后等于两个时间戳。
if (equalsWithYesterday(items.get(i).date)){
...
}
...
public boolean equalsWithYesterday(Timestamp st){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // Time part has discarded
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = dateFormat.parse(dateFormat.format(cal.getTime())); // get yesterday's Date without time part
Date srcDate = new Date(st);
Date srcDateWithoutTime =dateFormat.parse(dateFormat.format(srcDate));
return yesterday.equals(srcDateWithoutTime ); // checks src date equals yesterday.
}
答案 1 :(得分:2)
您可以将timestamp对象转换为日期对象,如下所示:
Date date = new Date(items.get(i).getTime());
或者您只需使用方法Timestamp#compareTo(Date o)
即可items.get(i).compareTo(yesterday_date);
答案 2 :(得分:1)
我希望你对比较时间不感兴趣?
只需使用Calendar课程从日期中提取日,月,年等,然后进行比较。
使用Calendar#get()方法从日期对象中获取特定字段。
如何从当前日期减去一天?
// get Calendar with current date
Calendar cal = Calendar.getInstance();
// get yesterday's date
cal.add(Calendar.DATE, -1);
// get components of yesterday's date
int month = cal.get(Calendar.MONTH) + 1; // 0 for January, 1 for Feb and so on
int day = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);
// get yesterday's date in milliseconds
long lMillis = cal.getTime().getTime();