記錄JAVA中Calendar類的一個問題

記錄一些不難可是須要費些勁的小需求,以備忘記時能夠查詢,避免浪費時間,也但願能幫助到其餘人html

1、需求
展現每月涉及周的周頭尾時間
image.png
2、實現過程
一、獲取某一日期所在周的週一和週日
這裏產品要求的是週一算一週的起點,和java默認的實現不一樣,因此實現的方法以下:java

//獲取周第一天
public static String getFirstDayOfWeek(Calendar calold) {  
        Calendar cal = (Calendar) calold.clone();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Date date = cal.getTime();  
        return Tools.getTimeByFormat(date, "yyyy-MM-dd");  
    }
//獲取周最後一天    
public static String getEndDayOfWeek(Calendar calold) {  
        Calendar cal = (Calendar) calold.clone();  
        cal.add(Calendar.DAY_OF_YEAR, 7);  
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);  
        Date date = cal.getTime();  
        return Tools.getTimeByFormat(date, "yyyy-MM-dd");  
    }

二、獲取月第一天傳到第一步的方法裏,獲取展現所需的字符串,下面就舉例:數組

public static String getMonthFirstDayWeekStr(@NotNull Calendar calold, int f) {  
    Calendar cale = (Calendar) calold.clone();  
    cale.add(Calendar.MONTH, 0);  
    cale.set(Calendar.DAY_OF_MONTH, 1);  
    Date date = cale.getTime();  
    //LogUtil.v("datestr", Tools.getTimeByFormat(date, "MM-dd"));
    if (f >= 1)  
        cale.add(Calendar.DAY\_OF\_YEAR, f \* 7);  
    return getFirstDayOfWeek(cale);  
}

運行以後發現,獲取日期有誤,
cale.set(Calendar.DAY_OF_MONTH, 1)
這一步始終無效,幾番嘗試無果以後,添加了上面註釋中的打印日誌的代碼,以後運行成功。
隨後我用java代碼嘗試了下,驗證了getTime這個方法使對Calendar的設置生效了;進一步看源碼發現,是由於調用了Calendar中的updatetime方法,進一步調用了computeTime方法;隨後到實現類GregorianCalendar中看了相關的代碼,computeTime方法中有這樣一句代碼。app

// Set this calendar's time in milliseconds  
  time = millis;

再結合calendar中updatetime和fileds字段的註釋發現Calendar中有兩套字段記錄時間,一個是long型的time記錄毫秒數;一個是int數組fields記錄着各類時間的字段。這裏貼一段註釋函數

// Calendar contains two kinds of time representations: current "time" in  
// milliseconds, and a set of calendar "fields" representing the current time.  
// The two representations are usually in sync, but can get out of sync  
// as follows.  
// 1. Initially, no fields are set, and the time is invalid.  
// 2. If the time is set, all fields are computed and in sync.  
// 3. If a single field is set, the time is invalid.  
// Recomputation of the time and fields happens when the object needs  
// to return a result to the user, or use a result for a computation.

可見,Calendar中真正記錄時間的time字段,而在咱們用設置field也就是年月日等字段時,並無馬上同步到time,而只是改變了field;當調用add、gettime等方法時,在updatetime方法中會進行同步,將field的改變同步到time字段,此時才真正改變了時間。
3、延申
一、經過研究代碼,解決的幾個工具上的小問題
a、在AndroidStudio中運行Java程序工具

add右鍵new moudle->選擇java libarary->在Class中添加main函數->運行鍵左側下拉 edit configurations->添加Application->分別配置main class爲main函數所在類,working directory爲mainclass所在目錄,useclasspathofmoudle爲添加的moudle,完成後就能夠運行

b、在Android studio中關聯java源碼,能夠查看代碼
File -> OtherSettings -> Default Project Structure或者
File -> Default Project Structure->將JDK Location選擇爲本身下載的jdk的位置;
備用方法:若是上面的方法遇到問題,可將jdk目錄中的src.zipjavafx-src.zip拷貝到AS默認的jre目錄下
4、參考連接
As中運行java程序
Java-Calendar「陷阱」
Android Studio關聯JDKJava 源碼this

相關文章
相關標籤/搜索