編輯:關於 Android 程式設計
日期計算幾乎每個專案都會遇到:本週一、上個月最後一天、本年第幾天、兩個日期相差幾日。Java 的 Calendar 搭配 SimpleDateFormat 就能處理絕大部分需求,以下整理成一個可直接取用的工具類。
public static int getYear() { return Calendar.getInstance().get(Calendar.YEAR); }
public static int getMonth() { return Calendar.getInstance().get(Calendar.MONTH) + 1; }
public static int getDayOfYear() { return Calendar.getInstance().get(Calendar.DAY_OF_YEAR); }
public static int getDayOfMonth() { return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); }
public static int getDayOfWeek() { return Calendar.getInstance().get(Calendar.DAY_OF_WEEK); }
public static int getWeekOfMonth(){ return Calendar.getInstance().get(Calendar.DAY_OF_WEEK_IN_MONTH); }
要注意 Calendar.MONTH 是從 0 開始,所以取月份時要加 1。
public String getNowTime(String dateformat) {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);
return dateFormat.format(now);
}
public static String convertDateToString(Date dateTime) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(dateTime);
}
public static Date strToDate(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
return formatter.parse(strDate, pos);
}
/** 依日期回傳星期名稱 */
public static String getWeek(String sdate) {
Date date = strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(date);
return new SimpleDateFormat("EEEE").format(c.getTime());
}
public static long getDays(String date1, String date2) {
if (date1 == null || date1.equals("")) return 0;
if (date2 == null || date2.equals("")) return 0;
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
try {
java.util.Date d1 = myFormatter.parse(date1);
java.util.Date d2 = myFormatter.parse(date2);
return (d1.getTime() - d2.getTime()) / (24 * 60 * 60 * 1000);
} catch (Exception e) {
return 0;
}
}
核心技巧是「先 set 到第一天,再用 add 跳到目標月份,最後用 -1 天退回上個月的月底」,這樣就不必自己判斷大小月。
/** 本週一(以週一為一週起始) */
private int getMondayPlus() {
Calendar cd = Calendar.getInstance();
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek == 1) {
return 0;
} else {
return 1 - dayOfWeek;
}
}
public String getMondayOFWeek() {
weeks = 0;
int mondayPlus = this.getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus);
return DateFormat.getDateInstance().format(currentDate.getTime());
}
public String getCurrentWeekday() { // 本週日
weeks = 0;
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, this.getMondayPlus() + 6);
return DateFormat.getDateInstance().format(currentDate.getTime());
}
public String getPreviousWeekday() { // 上週一
weeks--;
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, this.getMondayPlus() + 7 * weeks);
return DateFormat.getDateInstance().format(currentDate.getTime());
}
public String getNextMonday() { // 下週一
weeks++;
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, this.getMondayPlus() + 7);
return DateFormat.getDateInstance().format(currentDate.getTime());
}
/** 本月第一天 */
public String getFirstDayOfMonth() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);
return sdf.format(lastDate.getTime());
}
/** 本月最後一天 */
public String getDefaultDay() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1); // 設為本月 1 號
lastDate.add(Calendar.MONTH, 1); // 加一個月,變下月 1 號
lastDate.add(Calendar.DATE, -1); // 退一天,變本月最後一天
return sdf.format(lastDate.getTime());
}
/** 上月最後一天 */
public String getPreviousMonthEnd() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH, -1);
lastDate.set(Calendar.DATE, 1);
lastDate.roll(Calendar.DATE, -1);
return sdf.format(lastDate.getTime());
}
/** 下月第一天 */
public String getNextMonthFirst() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH, 1);
lastDate.set(Calendar.DATE, 1);
return sdf.format(lastDate.getTime());
}
/** 今年最後一天 */
public String getCurrentYearEnd() {
Date date = new Date();
String years = new SimpleDateFormat("yyyy").format(date);
return years + "-12-31";
}
public String getThisSeasonFirstTime(int month) {
int[][] array = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12} };
int season = 1;
if (month >= 1 && month <= 3) season = 1;
if (month >= 4 && month <= 6) season = 2;
if (month >= 7 && month <= 9) season = 3;
if (month >= 10 && month <= 12) season = 4;
int startMonth = array[season - 1][0];
String years = new SimpleDateFormat("yyyy").format(new Date());
return Integer.parseInt(years) + "-" + startMonth + "-1";
}
/** 取得指定年月的天數 */
private int getLastDayOfMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12) {
return 31;
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
if (month == 2) {
return isLeapYear(year) ? 29 : 28;
}
return 0;
}
public boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
類別中還有 getPreviousYearFirst()、getNextYearEnd()、getTimeYearNext()(加 183 天取半年後)等方法,實作思路都相同,只是 add() 的欄位與位移量不同。
第一,Calendar 的 add() 與 roll() 差別在於是否進位:add() 會連帶改動更大的欄位(加一個月會影響年份),roll() 則只在該欄位內循環。第二,日期相減用毫秒差除以一天的毫秒數是常見寫法,但遇到日光時間或時區變動時可能產生誤差,若要求嚴謹可改用 java.time 的 ChronoUnit.DAYS.between()。第三,在多線程環境中 SimpleDateFormat 並非執行緒安全,請勿共用同一個實例,建議每次建立或改用 DateTimeFormatter。
高仿微信圖片選擇器:Android 海量圖片的掃描、加載與流暢體驗
一、為什麼要認真對待圖片加載 手機鏡頭的像素輕鬆破千萬,一張照片解釋成 Bitmap 之後所佔的內存往往相當可觀。如果直接把幾千張原圖一股腦塞進列表,閃退與卡頓幾乎是必然
Android 入門必讀:從通信世代到你的第一個 App
一、先搞懂 1G、2G、3G、4G 到底在說什麼 我們常把行動網路講成「幾 G」,這個 G 其實是 Generation(世代)的縮寫,用來標示行動通訊技術的演進階段。從
掌握 Android 視窗顯示狀態:requestWindowFeature() 的實際應用
在日常開發中,我們經常會遇到諸如「讓程式全屏顯示」、「自訂標題列(例如在標題上放入按鈕等控制項)」之類的需求。今天這一篇,就來談談如何靈
Android 對話框樣式大全:以 jjdxm-dialogui 快速搞定各種彈窗
簡介 專案裡的彈窗需求往往五花八門:提示、確認、單選、多選、輸入、底部選單、自訂版面……每一種都自己寫一遍,程式碼很快就失控了。jjdxm-dialogui 這個庫把常見