How to get dates of a week (I know week number)?

后端 未结 5 1972
猫巷女王i
猫巷女王i 2020-12-01 11:16

I know the week number of the year, a week is start from Sunday, then Monday, Tuesday...,Saturday.

Since I know the week number, what\'s the efficient way to get the

相关标签:
5条回答
  • 2020-12-01 11:27

    You did not mention what return type do you exactly need but this code should prove useful to you. sysouts and formatter are just to show you the result.

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.WEEK_OF_YEAR, 30);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    System.out.println(formatter.format(cal.getTime()));
    cal.add(Calendar.DAY_OF_WEEK, 6);
    System.out.println(formatter.format(cal.getTime()));
    
    0 讨论(0)
  • 2020-12-01 11:28

    You can use the joda time library

    int weekNumber = 10;
    DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekNumber);
    DateTime weekEndDate = new DateTime().withWeekOfWeekyear(weekNumber + 1);
    
    0 讨论(0)
  • 2020-12-01 11:29

    Pure Java 8 / java.time solution

    Based on this:

    final long calendarWeek = 34;
    LocalDate desiredDate = LocalDate.now()
                .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, calendarWeek)
                .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    
    0 讨论(0)
  • 2020-12-01 11:33

    If you don't want external library, just use calendar.

    SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.WEEK_OF_YEAR, 23);        
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    System.out.println(sdf.format(cal.getTime()));    
    
    0 讨论(0)
  • 2020-12-01 11:39

    This answer is pretty much same as others. But, here it goes:

    int year = 2018;
    int week = 27;
    int day = 1; //assuming week starts from sunday
    Calendar calendar = Calendar.getInstance();
    calendar.setWeekDate(year, week, day);
    System.out.println(calendar.getTime());
    
    0 讨论(0)
提交回复
热议问题