1. 程式人生 > >Java 獲取當前日期的幾種方法

Java 獲取當前日期的幾種方法

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class getCurrDate {
	public static void main(String[] args) {
		getCurrDateTime04();
	}
	
	public static void getCurrDateTime01() {
		Date day = new Date();
		SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HHmmss" );
		String dateTime = df.format( day );
		
		System.out.println( dateTime );
	}
	
	public static void getCurrDateTime02() {
		SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HHmmss" );
		String dateTime = df.format( System.currentTimeMillis() );
		
		System.out.println( dateTime );
	}
	
	public static void getCurrDateTime03() {
		Calendar cal = Calendar.getInstance(); // 可以對每個時間域單獨修改
		int year   = cal.get( Calendar.YEAR        );
		int month  = cal.get( Calendar.MONTH       );
		int date   = cal.get( Calendar.DATE        );
		int hour   = cal.get( Calendar.HOUR_OF_DAY );
		int minute = cal.get( Calendar.MINUTE      );
		int second = cal.get( Calendar.SECOND      );
		System.out.println( year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second );
		
		DateFormat dateFormat = DateFormat.getDateInstance( DateFormat.FULL );
		Date dateTime = cal.getTime();
		String dateStr = dateFormat.format( dateTime );
		System.out.println( dateTime );
		System.out.println( dateStr );
	}
	
	public static void getCurrDateTime04() {
		Date date = new Date();
		String year   = String.format( "%tY", date );
		String month  = String.format( "%tm", date );
		String day    = String.format( "%td", date );
		String hour   = String.format( "%tH", date );
		String minute = String.format( "%tM", date );
		String second = String.format( "%tS", date );
		String millisecond = String.format( "%tL", date );

		System.out.println(  year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + ":" + millisecond );
	}
}