利用Calendar获取Date中的年、月、日、时、分、秒等

java.util.Date中提供的getYear()、getMonth()、getDay()等已经不建议使用了。

 

这里我们可以使用java.util.Calendar来替代完成,并且该类还提供了更多实用的扩展功能。

 

 

package org.liw.date;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import com.ibm.icu.text.SimpleDateFormat;

/**
 * Calendar、Date、SimpleDateFormat
 * @author lee.will
 *
 */
public class TestCalendar {
	
	/**
	 * 日期格式
	 */
	public static final String DATE_FORMAT = "yyyy.MM.dd HH:mm:ss";
	
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {

		//将日期字符串转换为日期
		Date dateTime = null;
		String dateTimeStr = "2011.08.18 14:20:35";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
		try {
			dateTime = simpleDateFormat.parse(dateTimeStr);
		} catch (ParseException e) {
			System.err.println("日期字符串 转换到 日期出错.");
			System.exit(1);
		}
		
		//日期转换为日历并获取参数
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dateTime);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);//Calendar.HOUR为12小时制
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
		String weekDayStr = turnWeekDaytoUpperCase(weekDay);
		
		//组织数据打印输出
		StringBuffer info = new StringBuffer();
		info.append(year).append("年").append(month).append("月").append(day).append("日")
		.append("\t")
		.append(hour).append(":").append(minute).append(":").append(second)
		.append("\t")
		.append("星期").append(weekDayStr);
		System.out.println(info);
	}
	
	/**
	 * 转换日期小写为大写
	 * @param weekDay
	 * @return
	 */
	private static String turnWeekDaytoUpperCase(int weekDay) {
		String weekDayStr = null;
		switch (weekDay) {
		case 1:
			weekDayStr = "一";
			break;
		case 2:
			weekDayStr = "二";
			break;
		case 3:
			weekDayStr = "三";
			break;
		case 4:
			weekDayStr = "四";
			break;
		case 5:
			weekDayStr = "五";
			break;
		case 6:
			weekDayStr = "六";
			break;
		default:
			weekDayStr = "日";
			break;
		}
		return weekDayStr;
	}
}

你可能感兴趣的:(Date)