http://www.verejava.com/?id=16993050424091
/**
知识点:Calandar 日期处理类
*/
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TestCalendar {
public static void main(String[] args) {
//实例化 Calandar 对象
Calendar c = new GregorianCalendar();
//输出年,月,日,时,分,秒
System.out.println(c.get(Calendar.YEAR));
//注意:Gregorian日历1月从 0 开始所以要加1
System.out.println(c.get(Calendar.MONTH) + 1);
System.out.println(c.get(Calendar.DATE));
System.out.println(c.get(Calendar.HOUR));
System.out.println(c.get(Calendar.MINUTE));
System.out.println(c.get(Calendar.SECOND));
System.out.println(c.get(Calendar.MILLISECOND));
//获得当前日期
System.out.println(DateTime.getDate());
//获得当前日期时间
System.out.println(DateTime.getDateTime());
//获得当前日期时间戳
System.out.println(DateTime.getTimeStamp());
}
}
/**
日期类的封装
1. 取得当前日期
2. 取得当前日期时间
3. 取得当前时间戳
*/
class DateTime {
//取得当前日期
public static String getDate() {
Calendar c = new GregorianCalendar();
StringBuffer buffer = new StringBuffer();
buffer.append(c.get(Calendar.YEAR)).append("-");
buffer.append(addZero(c.get(Calendar.MONTH) + 1)).append("-");
buffer.append(addZero(c.get(Calendar.DATE)));
return buffer.toString();
}
//取得当前日期时间
public static String getDateTime() {
Calendar c = new GregorianCalendar();
StringBuffer buffer = new StringBuffer();
buffer.append(c.get(Calendar.YEAR)).append("-");
buffer.append(addZero(c.get(Calendar.MONTH) + 1)).append("-");
buffer.append(addZero(c.get(Calendar.DATE))).append(" ");
buffer.append(addZero(c.get(Calendar.HOUR))).append(":");
buffer.append(addZero(c.get(Calendar.MINUTE))).append(":");
buffer.append(addZero(c.get(Calendar.SECOND)));
return buffer.toString();
}
//获取当前时间戳
public static long getTimeStamp() {
Calendar c = new GregorianCalendar();
return c.getTime().getTime();
}
//如果月,日,时,分,秒小于 10 在前面添加0
public static String addZero(int value) {
String str = Integer.toString(value);
if (str.length() < 2)
return 0 + str;
return str;
}
}