简体   繁体   中英

How to get the date of a specific day in a specific week

I wanto to get the date of a specific day in a specific week, identified by the week number.

Here's an example:

Today it is Monday (03.10.2016) and it is the week with the number 58. Now i want to get the date of eg Friday of this week.

I use Joda-Time within my android application.

Currently Iam creating a LocalDate.

    // This is the date of today
private LocalDate reportDate = new LocalDate();

// The number of the week is calculated here
int week = Weeks.weeksBetween(startDate.dayOfWeek().withMinimumValue().minusDays(1),
        reportDate.dayOfWeek().withMaximumValue().plusDays(1)).getWeeks();

switch(day_of_week) {
    case "Monday":
        // Get date of this day in current week
        break;
    case "Tuesday":
        // Get date of this day in current week
        break;
    // ...

You can use following code to achieve the days as desired,

    LocalDateTime yourDate = LocalDateTime.now();
    System.out.println(yourDate.getWeekOfWeekyear());
    int weekOfyear = yourDate.getWeekOfWeekyear();
    //Fetch Week Start Date for Given Week Number
    DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekOfyear);
    System.out.println(weekStartDate.toString());
    //Fetch Specific Days for given week
    DateTime wedDateTime = weekStartDate.withDayOfWeek(DateTimeConstants.WEDNESDAY);

I hope this answer your query.

As per my understanding of your requirement I have implemented below code, just check if it helps you,

First Import Calendar Package As Below

import java.util.Calendar;

Now Create below function

public String getSpecificDate(int weekOfYear, int dayOfWeek)
{    

   Calendar cal = Calendar.getInstance();

    cal.set(Calendar.WEEK_OF_YEAR, weekOfYear);
    cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);

    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);      // 0 to 11
    int day = cal.get(Calendar.DAY_OF_MONTH);

    String selectedDate = " " + day + "-" +  (month+1) + "-" + year;
    return selectedDate;
}

// I have passed getSpecificDate(41, 6) and get 7-10-2016 as output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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