如何在java获取一组时间列表的最近时间(for循环输出的一组时间)?
2个回答
展开全部
List<String> list = new ArrayList<String>();
list.add("2012-11-01 12:12:20");
list.add("2012-11-01 12:13:20");
list.add("2012-11-01 12:10:20");
list.add("2012-10-31 12:14:20");
list.add("2012-11-01 11:14:20");
System.out.println(Arrays.toString(list.toArray()));
Date later = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(String date:list){
try{
if(later == null){
later = sdf.parse(date);
}else{
if(later.before(sdf.parse(date))){
later = sdf.parse(date);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println(sdf.format(later));
list.add("2012-11-01 12:12:20");
list.add("2012-11-01 12:13:20");
list.add("2012-11-01 12:10:20");
list.add("2012-10-31 12:14:20");
list.add("2012-11-01 11:14:20");
System.out.println(Arrays.toString(list.toArray()));
Date later = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(String date:list){
try{
if(later == null){
later = sdf.parse(date);
}else{
if(later.before(sdf.parse(date))){
later = sdf.parse(date);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println(sdf.format(later));
追问
得出最大时间后,怎么得到现在(此刻)的时间和最大(得到的)的时间的差?
追答
public static void main(String[] args) {
List list = new ArrayList();
list.add("2012-11-01 12:12:20");
list.add("2012-11-01 12:13:20");
list.add("2012-11-01 12:10:20");
list.add("2012-10-31 12:13:20");
list.add("2012-11-01 11:14:20");
System.out.println(Arrays.toString(list.toArray()));
Date later = null;
Date prior = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (String date : list) {
try {
if (later == null) {
later = sdf.parse(date);
prior = sdf.parse(date);
} else {
if (later.before(sdf.parse(date))) {
later = sdf.parse(date);
}
if(prior.after(sdf.parse(date))) {
prior = sdf.parse(date);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("最近时间:"+sdf.format(later));
System.out.println("最远时间:"+sdf.format(prior));
//相减
long time = later.getTime() - prior.getTime();
String result = "";
//转成分钟
time = time/60000;
//判断是否超过一天
if(time/60>=24){
result = time/60/24 + "天";
}else{
if(time/60==0){
result = time + "分钟";
}else{
result = time/60 + "小时";
}
}
System.out.println(result);
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询