簡體   English   中英

如何在Android中的兩個日期之間獲取星期間隔?

[英]How to get week interval in between two dates in android?

嗨,我正在編寫代碼,以顯示當前時間和登錄時間之間的星期間隔,

我添加了一個可以節省登錄時間的功能。

public void setWeek() {
    Date today = new Date();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String dateToStr = format.format(today);
    editor.putString("week", dateToStr).commit();
}

public String getWeek() {
    return pref.getString("week", null);
}

這將幫助您。 我使用此條件從輸入日期獲取了天數,並檢查是否有7天可以運行我的條件。

call conditionForWeek(){
    calendarToday = Calendar.getInstance();
        formatInstallDate = new SimpleDateFormat(FORMAT_DATE_DD_MMM_YY, Locale.ENGLISH);
        currentDate = formatInstallDate.format(calendarToday.getTime());
        installDate = PreferencesManager.getInstance().getString(USER_DATE_OF_INSTALL);

        int differenceInDate = PregnancyAppUtils.getDaysBetweenDates(currentDate, installDate);

        if (differenceInDate > 0 && differenceInDate % 7 == 0) {
                CallYourConditionHere();
        }
}


//This method will calculate difference in days and return the difference in days

    @SuppressLint("SimpleDateFormat")
    public static int getDaysBetweenDates(String currentDate, String installDate) {
        formatConversion = new SimpleDateFormat(FORMAT_DATE_DD_MMM_YY);
        try {
            Date dateCurrent = formatConversion.parse(currentDate);
            Date dateAfterSevenDays;
            //take care of previous app version's date formats
            try {
                dateAfterSevenDays = formatConversion.parse(installDate);
            } catch (ParseException e) {
                dateAfterSevenDays = getCalObjFromDefaultDate(installDate).getTime();
            }
            differenceInDate = dateCurrent.getTime() - dateAfterSevenDays.getTime();
            days = (int) (differenceInDate / (1000 * 60 * 60 * 24));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

下面的方法計算兩個日期之間的星期數。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = dateFormat.parse("2019-01-01");
Date endDate = dateFormat.parse("2019-01-29");
int noOfWeek = calculateWeekNo(startDate, endDate);

   //Option 1
   public int calculateWeekNo(Date start, Date end) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(start);
        int weeks = 0;
        while (cal.getTime().before(end)) {
            cal.add(Calendar.WEEK_OF_YEAR, 1);
            weeks++;
        }
       return weeks;
    }

   // Option 2
    public static int calculateWeekNo(Date start, Date end) {
         Calendar a = new GregorianCalendar();
         Calendar b = new GregorianCalendar();
         a.setTime(start);
         b.setTime(end);
         return b.get(Calendar.WEEK_OF_YEAR) - a.get(Calendar.WEEK_OF_YEAR);
       }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM