Java基础----Date+Calender+DataFormatter

DateDemo:

public class DateDemo {

	public static void main(String[] args) throws ParseException {

		methodDemo_3();		
	}
	
	/**
	 * 将日期格式的字符串-->日期对象。
	 * 	使用的是DateFormat类中的parse()方法。 
	 * 
	 * @throws ParseException 
	 */
	public  static void methodDemo_3() throws ParseException {
		
		String str_date = "2012年4月19日";
		str_date = "2011---8---17";
			
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG);
		
		dateFormat = new SimpleDateFormat("yyyy---MM---dd");
		
		Date date = dateFormat.parse(str_date);
		
		System.out.println(date);
			
	}

	/**
	 * 对日期对象进行格式化。
	 * 将日期对象-->日期格式的字符串。
	 * 	使用的是DateFormat类中的format方法。
	 */
	public static void methodDemo_2() {
		
		Date date = new Date();
		
		//获取日期格式对象。具体着默认的风格。 FULL LONG等可以指定风格。
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG);
		dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
//		System.out.println(dateFormat);
		
		//如果风格是自定义的如何解决呢?
		dateFormat = new SimpleDateFormat("yyyy--MM--dd");
		
		String str_date = dateFormat.format(date);
		
		System.out.println(str_date);
	}
			
	/**
	 * 日期对象和毫秒值之间的转换。
	 * 
	 * 毫秒值-->日期对象 : 
	 * 	1,通过Date对象的构造方法  new Date(timeMillis);
	 *  2,还可以通过setTime设置。 
	 *  因为可以通过Date对象的方法对该日期中的各个字段(年月日等)进行操作。
	 *   
	 * 日期对象-->毫秒值:
	 * 	2,getTime方法。
	 * 因为可以通过具体的数值进行运算。 
	 * 
	 */
	public static void methodDemo_1() {
		long time = System.currentTimeMillis();//
//		System.out.println(time);//1335671230671
		
		Date date = new Date();//将当前日期和时间封装成Date对象。
		System.out.println(date);//Sun Apr 29 11:48:02 CST 2012
		
		Date date2 = new Date(1335664696656l);//将指定毫秒值封装成Date对象。
		System.out.println(date2);
	}
}

CakenderDemo:

public class CalendarDemo {

	public static void main(String[] args) {

		Calendar c = Calendar.getInstance();
		
		int year = 2012;
		showDays(year);
	}

	public static void showDays(int year) {
		
		Calendar c = Calendar.getInstance();
		c.set(year, 2, 1);
		
		c.add(Calendar.DAY_OF_MONTH, -1);
		
		showDate(c);
	}

	public static void showDate(Calendar c) {
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH)+1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		int week = c.get(Calendar.DAY_OF_WEEK);
		
		System.out.println(year+"年"+month+"月"+day+"日"+getWeek(week));
	}

	public static String getWeek(int i) {
		
		String[] weeks = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
		
		return weeks[i];
	}
}

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值