发现朋友做一个项目,然后涉及到年、月、日的加减。他居然自己定义了24小时,31天,12个月几个数组,然后自己写逻辑运算。首先不说自己写出来有没有BUG,至少肯定代码有点多,而且还要判断闰年。Java在很早的版本中已经提供了时间操作类,JDK1.1好像就有Calendar日期操作类,利用它,你随意运算,而且代码量非常小。
以下例子是建立在每次更改之后的时间,并不是每次都是当前时间。
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
System.out.println("现在时间");
Calendar calendar = Calendar.getInstance();
System.out.println(sdf.format(new Date(calendar.getTimeInMillis())));
int day = calendar.get(Calendar.DAY_OF_YEAR);
// 30天前
calendar.set(Calendar.DAY_OF_YEAR, day - 30);
System.out.println("30天前");
System.out.println(sdf.format(new Date(calendar.getTimeInMillis())));
// 78小时前
int hour = calendar.get(Calendar.HOUR_OF_DAY);
calendar.set(Calendar.HOUR_OF_DAY, hour - 78);
System.out.println("78小时前");
System.out.println(sdf.format(new Date(calendar.getTimeInMillis())));
int second = calendar.get(Calendar.SECOND);
calendar.set(Calendar.SECOND, second - 5362);
System.out.println("5362秒前");
System.out.println(sdf.format(new Date(calendar.getTimeInMillis())));

时间解析:
public static void main(String[] args) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
// 2015-11-8 0:59:54
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse("2015-11-8 0:59:54");
c.setTime(date);
System.out.print(c.get(Calendar.YEAR));
System.out.print(c.get(Calendar.MONTH) + 1);
System.out.print(c.get(Calendar.DAY_OF_MONTH));
System.out.print(c.get(Calendar.HOUR_OF_DAY));
System.out.print(c.get(Calendar.MINUTE));
System.out.print(c.get(Calendar.SECOND));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
本文链接:https://it72.com:4443/3612.htm