java中日期时间格式与毫秒数的转换

//输入日期转化为毫秒数 ---用calendar方法(calendar.getTime)
		Calendar calendar = Calendar.getInstance();
		calendar.set(2018, 2, 15, 8, 31, 5);
		System.out.println(calendar.getTimeInMillis());


//输入日期,转化为毫秒数,用DATE方法()
		/**
		 * 先用SimpleDateFormat.parse() 方法将日期字符串转化为Date格式
		 * 通过Date.getTime()方法,将其转化为毫秒数
		 */
		String date = "2001-03-15 15-37-05";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//24小时制
//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制
		long time2 = simpleDateFormat.parse(date).getTime();
		System.out.println(time2);


//输入毫秒数,转化为日期,用simpleDateFormat  +  Date 方法;
		/**
		 * 直接用SimpleDateFormat格式化 Date对象,即可得到相应格式的日期 字符串。
		 */
		long time3 = System.currentTimeMillis() + 5000 *1000;
		
		Date date2 = new Date();
		date2.setTime(time3);
		System.out.println(simpleDateFormat.format(date2));


//输入毫秒数,转化为日期,用calendar方法;
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTimeInMillis(time3);
		int year = calendar2.get(Calendar.YEAR);
		int month = calendar2.get(Calendar.MONTH);
		int day = calendar2.get(Calendar.DAY_OF_MONTH);
		int hour = calendar2.get(Calendar.HOUR_OF_DAY);//24小时制
//		int hour = calendar2.get(Calendar.HOUR);//12小时制
		int minute = calendar2.get(Calendar.MINUTE);
		int second = calendar2.get(Calendar.SECOND);
		
		System.out.println(year + "年" + (month + 1) + "月" + day + "日"
				+ hour + "时" + minute + "分" + second + "秒");




你可能感兴趣的:(java,时间,日期,转化,毫秒数)