1. 程式人生 > >java 獲取當前日期時間

java 獲取當前日期時間

public class MyDate {
	
	private static String[] week=
	{
		"日","一","二","三","四","五","六"		
	};
	
	// 獲取當前日期和時間
	public static String getCurrentDateStr()
	{
		StringBuilder dateStr = new StringBuilder();
		Calendar calendar = Calendar.getInstance();
		
		dateStr.append(calendar.get(Calendar.YEAR)+"年 ")
		       .append(calendar.get(Calendar.MONTH)+1+"月 ")
		       .append(calendar.get(Calendar.DAY_OF_MONTH)+"日 ")
		       .append("星期"+week[calendar.get(Calendar.DAY_OF_WEEK)-1])
		       .append((calendar.get(Calendar.AM_PM)==Calendar.AM)?" 上午 ":" 下午 ")
		       .append(calendar.get(Calendar.HOUR)+":")
		       .append(calendar.get(Calendar.MINUTE));
		return dateStr.toString();
	}
	
	// 將日期時間轉換成毫秒
	public static long getMillisecond(int year, int month, int dayOfMonth, int hour, int minute)
	{
		Calendar calendar = Calendar.getInstance();
		calendar.set(year,month,dayOfMonth,hour,minute);
		return calendar.getTimeInMillis();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Calendar calendar = Calendar.getInstance();
		long mi = getMillisecond(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE));
		
		System.out.println("-------"+mi);
		
		calendar.setTimeInMillis(mi);
		
		System.out.println(calendar.toString());
		
	}
	

}