Created
May 6, 2014 03:02
-
-
Save ssd863419/a3601b739654b39225be to your computer and use it in GitHub Desktop.
簡單練習Calendar, 還有當前月份的日曆顯示
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.SimpleDateFormat; | |
import java.util.Calendar; | |
import java.util.Date; | |
public class Test { | |
public static void main(String[] args) { | |
Calendar rightNow = Calendar.getInstance(); | |
System.out.println("Calendar.MONTH : " + rightNow.get(Calendar.MONTH)); | |
int month = rightNow.get(Calendar.MONTH)+1; | |
System.out.println("當前月份 : " + month); | |
System.out.println("Calendar.DAY_OF_MONTH : " + rightNow.get(Calendar.DAY_OF_MONTH)); | |
System.out.println("Calendar.YEAR : " + rightNow.get(Calendar.YEAR)); | |
System.out.println("當前時間 : " + rightNow.get(Calendar.HOUR_OF_DAY) + ":" + rightNow.get(Calendar.MINUTE) + ":" + rightNow.get(Calendar.SECOND)); | |
System.out.println("Calendar.DAY_OF_WEEK : " + rightNow.get(Calendar.DAY_OF_WEEK)); | |
int week = rightNow.get(Calendar.DAY_OF_WEEK)-1; | |
System.out.println("今天週幾 : " + week); | |
//計算天數差距 | |
SimpleDateFormat simpleDay = new SimpleDateFormat("yyyyMMdd"); | |
Calendar c1 = Calendar.getInstance(); | |
c1.set(2014 , 4-1 , 5); //2014/4/5 | |
Date d1 = c1.getTime(); | |
System.out.println("日期1 : " + simpleDay.format(d1)); | |
Calendar c2 = Calendar.getInstance(); | |
c2.set(2014 , 11-1 , 2); //2014/11/2 | |
Date d2 = c2.getTime(); | |
System.out.println("日期2 : " + simpleDay.format(d2)); | |
long dateDiff = (d2.getTime() - d1.getTime())/(24*60*60*1000); | |
System.out.println("2014-4-5 ~ 2014-11-2 差幾天 : " + dateDiff); | |
//顯示當前月份的日曆 | |
Calendar dateNow = Calendar.getInstance(); | |
//當月天數 | |
int monthDayNum = dateNow.getActualMaximum(Calendar.DATE); | |
//當月第一天是週幾 | |
dateNow.set(Calendar.DATE , 1); //設定dateNow為當天月份的第一天 | |
int firstDay = dateNow.get(Calendar.DAY_OF_WEEK)-1; | |
String [] titleWeek = {"日" , "一" , "二" , "三" , "四" , "五" , "六"}; | |
for (int i = 0; i < titleWeek.length; i++) { | |
System.out.print(titleWeek[i] + " "); | |
} | |
System.out.println(); | |
//第1天在週幾的情況, 前面對應的空格數 | |
for (int i = 0; i < firstDay; i++) { | |
System.out.print(" "); | |
} | |
for (int i = 1; i <= monthDayNum; i++) { | |
System.out.print(i); | |
if (i <10) { | |
System.out.print(" "); | |
}else { | |
System.out.print(" "); | |
} | |
if ((firstDay+i)%7 ==0){ | |
System.out.println(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment