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 + "秒");




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章