简体   繁体   English

在Android中获取给定星期数的日期

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

I would like to get dates for a given week number. 我想获取给定星期数的日期。 For Instance, if I have the week number as 15, I need to get dates: 05-04-2015, 06-04-2015, 07-04-2015, 08-04-2015, 09-04-2015, 10-04-2015, 11-04-2015 . 例如,如果我的星期数为15,则需要获取日期: 2015年5月4日,2015年6月4日,2015年4月4日,2015年4月4日,2015年9月4日, 04-2015,11-04-2015

Is this possible? 这可能吗? If so, how? 如果是这样,怎么办?

Let me know, 让我知道,

Thanks! 谢谢!

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);
}

public static void main(String[] args) { 公共静态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()));

} }

Here is my solution: 这是我的解决方案:

    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";
    }

As an input, except for the week, you need to have a year. 作为输入,除了星期外,您需要有一年。 Pay attention that the first day of week depends on Locale. 请注意,一周的第一天取决于语言环境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM