Java - Date - Calendar - DateFormat

Date类 表示特定的瞬间,精确到毫秒。从 JDK 1.1 开始,应该使用Calendar 类实现日期和时间字段之间转换,使用 DateFormat 类来格式化和解析日期字符串

DateFormat :可以自定义时间格式,对时间对象进行操作和解析。实现了时间对象到字符串,和字符串到时间对象的转换。

Calendar : 对时间对象(特定瞬间)各个属性的操作,如对时间的年月日时分秒的获取,修改,偏移。。

/****
	 * 
	 * 计算两个日期相差的天数
	 * 	 
	 */
	public static void main(String[] args) throws ParseException {
		String s1 = "2014.08.01";
		String s2 = "2014.09.03";
		//创建日期格式
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
		//解析字符串生成 Date
		Date date1 = simpleDateFormat.parse(s1);
		Date date2 = simpleDateFormat.parse(s2);
		//获取相差的毫秒
		long time = Math.abs(date1.getTime() - date2.getTime());
		//计算相差的天数
		int days = (int) (time / 1000 / 60 / 60 / 24);
		System.out.println(days);
	}

/***********
 *一天前的当前时刻 *
 *****/
public class DeteDemo {

	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		showDate(calendar);
	}

	private static void showDate(Calendar calendar) {
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int date = calendar.get(Calendar.DATE);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		String week = getWeek(calendar.get(Calendar.DAY_OF_WEEK));
		System.out.println(year + "年" + month + "月" + date + "日" + "-" + week);
		System.out.println(hour + ":" + minute + ":" + second);
	}

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值