当前时间

Calendar cal = Calendar.getInstance();  //实例化
Date today = new Date(); //Date类的当前时间

打印cal(类形式)

java.util.GregorianCalendar[time=1406185232225,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=30,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=205,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=0,SECOND=32,MILLISECOND=225,ZONE_OFFSET=28800000,DST_OFFSET=0]

获取相应字段

Date date = cal.getTime()  //当前时间,Date对象
int year = cal.get(Calendar.YEAR); //获取年份
int month = cal.get(Calendar.MONTH) + 1; //获取月份,注意要从0开始
int day = cal.get(Calendar.DATE);  //获取天数

int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);

时间转成String

SimpleDateFormat
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
String todaytime = formatter.format(today);
DateFormatUtils

需要用到commons-lang-2.4.jar的包

DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")

String转成时间

不要忘了加Locale.CANADA,要不然月份Jul解析不了,会出现unparseable。因为,simpleDateFormat会按当地时区进行解析,这时月份应为中文的七月才能解析。

String time = "05/Jul/2014:00:01:01";
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.CANADA);
cal.setTime(formatter.parse(time));

时间运算

Calendar提供add()方法进行运算,第一个参数指明字段,第二个参数为amount。要做减法,将amount置为负数即可。

cal.add(Calendar.HOUR, -1);

lifehack
134 声望6 粉丝