在android中获取一年中一周的日期

时间:2015-04-27 06:45:37

标签: android android-calendar

我正在尝试从给定的周数和年份中获取日期。即使我输入周和年,下面的代码总是显示当前日期。

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

而不是获取第15周的日期。我总是获得当前日期值。我不是这里的错误吗?

如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个

  Calendar now = Calendar.getInstance();
  now.set(Calendar.YEAR,2015);
  now.set(Calendar.WEEK_OF_YEAR,15);

  System.out.println(new SimpleDateFormat("yyyy.MM.dd").format(now.getTime()));
  

输出

enter image description here

答案 1 :(得分:0)

请更新我的代码:它对我有用。

  Calendar now = Calendar.getInstance();
      now.set(Calendar.YEAR,2015);
      now.set(Calendar.WEEK_OF_YEAR,15);


      String result = "";

        int firstDayOfWeek = now.getFirstDayOfWeek();

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

    Log.e("result","result:"+result);