Search code examples
javadatecalendargregorian-calendardate-parsing

How to determine the date passing the Week Number and Day Number (Week) in java


I need to get the date by passing these parameters

  1. year
  2. week number (in a month) i.e. 1,2,3,4,5
  3. day number (in a week) 0 (Sunday) to 6 (Saturday)
  4. Month

I looked for a constructor in Calendar class but does not contain these parameters.


Solution

  • To create date from year, week number and week's day use java.util.Calendar instance:

    Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, 2017);
            cal.set(Calendar.WEEK_OF_YEAR, 26);
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    

    To convert from Calendar to java.util.Date :

    Date date = cal.getTime();
    

    To convert Date into java.time.LocalDateTime use :

    LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());