簡體   English   中英

在Android中獲取給定星期數的日期

[英]Get dates for a given week number in Android

我想獲取給定星期數的日期。 例如,如果我的星期數為15,則需要獲取日期: 2015年5月4日,2015年6月4日,2015年4月4日,2015年4月4日,2015年9月4日, 04-2015,11-04-2015

這可能嗎? 如果是這樣,怎么辦?

讓我知道,

謝謝!

int yourYear = 1997;

Calendar c1 = Calendar.getInstance();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
c1.set(yourYear, 1, 1);
c1.add(Calendar.DATE, WEEK*7); 
for (int i = 0, i < 7; i++){
 String formatted = format1.format(cal.getTime());
 System.out.println(formatted);
 c1.add(Calendar.DATE, 1);
}

公共靜態void main(String [] args){

// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);

// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK, 
          first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));

// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);

// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " + 
                   df.format(last.getTime()));

}

這是我的解決方案:

    Calendar c = new GregorianCalendar(Locale.getDefault());
    c.set(Calendar.WEEK_OF_YEAR, 15);
    c.set(Calendar.YEAR, 2015);

    String result = "";

    int firstDayOfWeek = c.getFirstDayOfWeek();
    for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
        c.set(Calendar.DAY_OF_WEEK, i);
        result += new SimpleDateFormat("yyyy.MM.dd").format(c.getTime()) + "\n";
    }

作為輸入,除了星期外,您需要有一年。 請注意,一周的第一天取決於語言環境。

暫無
暫無

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

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