1. 获取系统时间可以通过Calendar或者Date默认构造函数或者实例得到,不过现在日期主要还是借助于Calendar来处理。另外还可以得到当前日期是一周的第几天(从星期天开始),一月以及一年的第几天
[java]
public static String getCurrentTime(){
Calendar c = Calendar.getInstance();
//HH 24 hour & hh 12 hour, E - week
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy E HH:mm:ss");
return sdf.format(c.getTime());
}
public static void printTodayInfo(){
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
System.out.println("Time for today:"+date.toString());
System.out.println("Day for today :"+c.get(Calendar.DAY_OF_WEEK));
System.out.println("Time for today:"+c.get(Calendar.DAY_OF_MONTH));
System.out.println("Time for today:"+c.get(Calendar.DAY_OF_YEAR));
}
2. 获取相较于当前时间的历史时间,如昨天、上周、上月、去年等
[java]
public static String getYesterday(){
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
return sdf.format(c.getTime());
}
public static String getLastMonth(){
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
return sdf.format(c.getTime());
}
public static String getLastYear(){
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -1);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
return sdf.format(c.getTime());
}
3. 设置一个历史时间
[java]
public static void setDate(){
Calendar c = Calendar.getInstance();
//note that the month start from 0
c.set(2013, 0, 25, 14, 48, 20);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println(sdf.format(c.getTime()));
String birthdate = "01/25/2012 13:11:12";
Date date = new Date();
try {
date = sdf.parse(birthdate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.setTime(date);
System.out.println(sdf.format(c.getTime()));
}
4. 时间与long型的对照关系,可以发现0对应的时间是 01/01/1970 08:00:00,以后每增加1s就要加上1000。这样借助于它我们也可以得到不同时间。
[java]
public static void checkLongAndDate(){
Calendar c = Calendar.getInstance();
c.setTimeInMillis(0);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//output is 01/01/1970 08:00:00
System.out.println(sdf.format(c.getTime()));
c.setTimeInMillis(c.getTimeInMillis()+1000*60*60*24);
System.out.println(sd