Time: How to get the next friday?












50















How can I get the next friday with the Joda-Time API.



The LocalDate of today is today. It looks to me you have to decide whever you are before or after the friday of the current week. See this method:



private LocalDate calcNextFriday(LocalDate d) {
LocalDate friday = d.dayOfWeek().setCopy(5);
if (d.isBefore(friday)) {
return d.dayOfWeek().setCopy(5);
} else {
return d.plusWeeks(1).dayOfWeek().setCopy(5);
}
}


Is it possible to do it shorter or with a oneliner?



PS: Please don't advise me using JDKs date/time stuff. Joda-Time is a much better API.



Java 8 introduces java.time package (Tutorial) which is even better.










share|improve this question




















  • 2





    good question... DateTime could use a rollForwardTo(...) method

    – skaffman
    Oct 28 '09 at 10:00











  • @skaffman See my generic rollForward answer. Its not super duper tested but seems to work for me.

    – Adam Gent
    Jul 18 '12 at 3:02






  • 1





    Actually, java.time is not necessarily better that Joda-Time. Each has features the other lacks. For example, java.time lacks the Interval class found in Joda-Time. So use each for its strengths. You can mix and match within a project. Just be careful with your import statements as a few of their classes share the same name.

    – Basil Bourque
    Apr 18 '15 at 19:38


















50















How can I get the next friday with the Joda-Time API.



The LocalDate of today is today. It looks to me you have to decide whever you are before or after the friday of the current week. See this method:



private LocalDate calcNextFriday(LocalDate d) {
LocalDate friday = d.dayOfWeek().setCopy(5);
if (d.isBefore(friday)) {
return d.dayOfWeek().setCopy(5);
} else {
return d.plusWeeks(1).dayOfWeek().setCopy(5);
}
}


Is it possible to do it shorter or with a oneliner?



PS: Please don't advise me using JDKs date/time stuff. Joda-Time is a much better API.



Java 8 introduces java.time package (Tutorial) which is even better.










share|improve this question




















  • 2





    good question... DateTime could use a rollForwardTo(...) method

    – skaffman
    Oct 28 '09 at 10:00











  • @skaffman See my generic rollForward answer. Its not super duper tested but seems to work for me.

    – Adam Gent
    Jul 18 '12 at 3:02






  • 1





    Actually, java.time is not necessarily better that Joda-Time. Each has features the other lacks. For example, java.time lacks the Interval class found in Joda-Time. So use each for its strengths. You can mix and match within a project. Just be careful with your import statements as a few of their classes share the same name.

    – Basil Bourque
    Apr 18 '15 at 19:38
















50












50








50


9






How can I get the next friday with the Joda-Time API.



The LocalDate of today is today. It looks to me you have to decide whever you are before or after the friday of the current week. See this method:



private LocalDate calcNextFriday(LocalDate d) {
LocalDate friday = d.dayOfWeek().setCopy(5);
if (d.isBefore(friday)) {
return d.dayOfWeek().setCopy(5);
} else {
return d.plusWeeks(1).dayOfWeek().setCopy(5);
}
}


Is it possible to do it shorter or with a oneliner?



PS: Please don't advise me using JDKs date/time stuff. Joda-Time is a much better API.



Java 8 introduces java.time package (Tutorial) which is even better.










share|improve this question
















How can I get the next friday with the Joda-Time API.



The LocalDate of today is today. It looks to me you have to decide whever you are before or after the friday of the current week. See this method:



private LocalDate calcNextFriday(LocalDate d) {
LocalDate friday = d.dayOfWeek().setCopy(5);
if (d.isBefore(friday)) {
return d.dayOfWeek().setCopy(5);
} else {
return d.plusWeeks(1).dayOfWeek().setCopy(5);
}
}


Is it possible to do it shorter or with a oneliner?



PS: Please don't advise me using JDKs date/time stuff. Joda-Time is a much better API.



Java 8 introduces java.time package (Tutorial) which is even better.







java date datetime time jodatime






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 18 '15 at 19:42









Basil Bourque

112k28385545




112k28385545










asked Oct 28 '09 at 9:16









michael.kebemichael.kebe

8,39823656




8,39823656








  • 2





    good question... DateTime could use a rollForwardTo(...) method

    – skaffman
    Oct 28 '09 at 10:00











  • @skaffman See my generic rollForward answer. Its not super duper tested but seems to work for me.

    – Adam Gent
    Jul 18 '12 at 3:02






  • 1





    Actually, java.time is not necessarily better that Joda-Time. Each has features the other lacks. For example, java.time lacks the Interval class found in Joda-Time. So use each for its strengths. You can mix and match within a project. Just be careful with your import statements as a few of their classes share the same name.

    – Basil Bourque
    Apr 18 '15 at 19:38
















  • 2





    good question... DateTime could use a rollForwardTo(...) method

    – skaffman
    Oct 28 '09 at 10:00











  • @skaffman See my generic rollForward answer. Its not super duper tested but seems to work for me.

    – Adam Gent
    Jul 18 '12 at 3:02






  • 1





    Actually, java.time is not necessarily better that Joda-Time. Each has features the other lacks. For example, java.time lacks the Interval class found in Joda-Time. So use each for its strengths. You can mix and match within a project. Just be careful with your import statements as a few of their classes share the same name.

    – Basil Bourque
    Apr 18 '15 at 19:38










2




2





good question... DateTime could use a rollForwardTo(...) method

– skaffman
Oct 28 '09 at 10:00





good question... DateTime could use a rollForwardTo(...) method

– skaffman
Oct 28 '09 at 10:00













@skaffman See my generic rollForward answer. Its not super duper tested but seems to work for me.

– Adam Gent
Jul 18 '12 at 3:02





@skaffman See my generic rollForward answer. Its not super duper tested but seems to work for me.

– Adam Gent
Jul 18 '12 at 3:02




1




1





Actually, java.time is not necessarily better that Joda-Time. Each has features the other lacks. For example, java.time lacks the Interval class found in Joda-Time. So use each for its strengths. You can mix and match within a project. Just be careful with your import statements as a few of their classes share the same name.

– Basil Bourque
Apr 18 '15 at 19:38







Actually, java.time is not necessarily better that Joda-Time. Each has features the other lacks. For example, java.time lacks the Interval class found in Joda-Time. So use each for its strengths. You can mix and match within a project. Just be careful with your import statements as a few of their classes share the same name.

– Basil Bourque
Apr 18 '15 at 19:38














7 Answers
7






active

oldest

votes


















57














java.time



With the java.time framework built into Java 8 and later (Tutorial) you can use TemporalAdjusters to get next or previous day-of-week.



private LocalDate calcNextFriday(LocalDate d) {
return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
}





share|improve this answer


























  • Does this uses joda-time?

    – Christopher Francisco
    May 26 '16 at 16:07






  • 2





    No, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

    – michael.kebe
    May 27 '16 at 19:40








  • 2





    FYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.

    – Basil Bourque
    Jun 30 '16 at 0:33





















52














It's possible to do it in a much easier to read way:



if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
return d.withDayOfWeek(DateTimeConstants.FRIDAY));
} else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
// almost useless branch, could be merged with the one above
return d;
} else {
return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
}


or in a bit shorter form



private LocalDate calcNextFriday(LocalDate d) {    
if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
} else {
d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
}
return d; // note that there's a possibility original object is returned
}


or even shorter



private LocalDate calcNextFriday(LocalDate d) {
if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
d = d.plusWeeks(1);
}
return d.withDayOfWeek(DateTimeConstants.FRIDAY);
}


PS. I didn't test the actual code! :)






share|improve this answer





















  • 2





    or compile it ... "DateTimeConstans"

    – David Victor
    Sep 14 '11 at 11:53






  • 8





    @David You saw nothing ;)

    – Esko
    Jan 23 '12 at 11:44






  • 5





    +1 for sense of humour. :)

    – David Victor
    Jan 23 '12 at 15:16











  • Your last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!

    – gyorgyabraham
    Aug 16 '13 at 15:32



















5














Your code in 1 line



private LocalDate calcNextFriday3(LocalDate d) {
return d.isBefore(d.dayOfWeek().setCopy(5))?d.dayOfWeek().setCopy(5):d.plusWeeks(1).dayOfWeek().setCopy(5);
}


Alternative approach



private LocalDate calcNextDay(LocalDate d, int weekday) {
return (d.getDayOfWeek() < weekday)?d.withDayOfWeek(weekday):d.plusWeeks(1).withDayOfWeek(weekday);
}


private LocalDate calcNextFriday2(LocalDate d) {
return calcNextDay(d,DateTimeConstants.FRIDAY);
}


somewhat tested ;-)






share|improve this answer



















  • 1





    Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.

    – michael.kebe
    Oct 28 '09 at 10:27






  • 5





    @michaelkebe you asked for a oneliner, I just provided one... ;-)

    – fvu
    Oct 28 '09 at 10:39






  • 1





    @michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.

    – gyorgyabraham
    Aug 16 '13 at 15:51



















4














I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.



Anyway here is my solution:



public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
DateTime dt = lp.toDateTime(now);
while (dt.isBefore(now)) {
dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
}
return dt;
}


Now you just need to make a Partial (which LocalDate is) for the day of the week.



Partial().with(DateTimeFieldType.dayOfWeek(), DateTimeConstants.FRIDAY); 


Now whatever the most significant field is of the partial will be +1 if the current date is after it (now).



That is if you make a partial with March 2012 it will create a new datetime of March 2013 or <.






share|improve this answer

































    4














    import java.util.Calendar;

    private Calendar getNextweekOfDay(int weekOfDay) {
    Calendar today = Calendar.getInstance();
    int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
    int daysUntilNextWeekOfDay = weekOfDay - dayOfWeek;
    if (daysUntilNextWeekOfDay == 0) daysUntilNextWeekOfDay = 7;
    Calendar nextWeekOfDay = (Calendar)today.clone();
    nextWeekOfDay.add(Calendar.DAY_OF_WEEK, daysUntilNextWeekOfDay);
    return nextWeekOfDay;
    }

    // set alarm for next Friday 9am
    public void setAlarm() {
    Calendar calAlarm = getNextweekOfDay(Calendar.FRIDAY);
    calAlarm.set(Calendar.HOUR_OF_DAY, 9);//9am
    calAlarm.set(Calendar.MINUTE, 0);
    calAlarm.set(Calendar.SECOND, 0);
    scheduleAlarm(calAlarm);// this is my own method to schedule a pendingIntent
    }





    share|improve this answer


























    • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

      – Basil Bourque
      Nov 30 '18 at 1:15



















    3














    counting bytes @fvu answer can be shortened even further to:



    private LocalDate calcNextFriday(LocalDate d) {
    return d.plusWeeks(d.getDayOfWeek() < DateTimeConstants.FRIDAY ? 0 : 1).withDayOfWeek(DateTimeConstants.FRIDAY);
    }





    share|improve this answer































      0














      A simple modulo based solution which should work with most of former java versions in case you are not allowed to upgrade your java version to java8 or onwards or to use a standard java date library as jodatime



      Number of days to add to your date is given by this formula :



      (7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7



      Note also this can be generalized for any week day by changing the static field Calendar.FRIDAY to your given weekday. Some snippet code below



      public static void main(String args) {
      for (int i = 0; i < 15; i++) {

      Calendar cur = Calendar.getInstance();
      cur.add(Calendar.DAY_OF_MONTH, i);

      Calendar friday = Calendar.getInstance();
      friday.setTime(cur.getTime());
      friday.add(Calendar.DAY_OF_MONTH, (7 + Calendar.FRIDAY - cur.get(Calendar.DAY_OF_WEEK)) % 7);

      System.out.println(MessageFormat.format("Date {0} -> {1} ", cur.getTime(), friday.getTime()));
      }
      }





      share|improve this answer


























      • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

        – Basil Bourque
        Nov 30 '18 at 1:14











      • Yes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.

        – Breton F.
        Dec 7 '18 at 15:26











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1636038%2ftime-how-to-get-the-next-friday%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      7 Answers
      7






      active

      oldest

      votes








      7 Answers
      7






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      57














      java.time



      With the java.time framework built into Java 8 and later (Tutorial) you can use TemporalAdjusters to get next or previous day-of-week.



      private LocalDate calcNextFriday(LocalDate d) {
      return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
      }





      share|improve this answer


























      • Does this uses joda-time?

        – Christopher Francisco
        May 26 '16 at 16:07






      • 2





        No, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

        – michael.kebe
        May 27 '16 at 19:40








      • 2





        FYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.

        – Basil Bourque
        Jun 30 '16 at 0:33


















      57














      java.time



      With the java.time framework built into Java 8 and later (Tutorial) you can use TemporalAdjusters to get next or previous day-of-week.



      private LocalDate calcNextFriday(LocalDate d) {
      return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
      }





      share|improve this answer


























      • Does this uses joda-time?

        – Christopher Francisco
        May 26 '16 at 16:07






      • 2





        No, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

        – michael.kebe
        May 27 '16 at 19:40








      • 2





        FYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.

        – Basil Bourque
        Jun 30 '16 at 0:33
















      57












      57








      57







      java.time



      With the java.time framework built into Java 8 and later (Tutorial) you can use TemporalAdjusters to get next or previous day-of-week.



      private LocalDate calcNextFriday(LocalDate d) {
      return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
      }





      share|improve this answer















      java.time



      With the java.time framework built into Java 8 and later (Tutorial) you can use TemporalAdjusters to get next or previous day-of-week.



      private LocalDate calcNextFriday(LocalDate d) {
      return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
      }






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jun 30 '16 at 0:31









      Basil Bourque

      112k28385545




      112k28385545










      answered Mar 12 '15 at 12:53









      michael.kebemichael.kebe

      8,39823656




      8,39823656













      • Does this uses joda-time?

        – Christopher Francisco
        May 26 '16 at 16:07






      • 2





        No, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

        – michael.kebe
        May 27 '16 at 19:40








      • 2





        FYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.

        – Basil Bourque
        Jun 30 '16 at 0:33





















      • Does this uses joda-time?

        – Christopher Francisco
        May 26 '16 at 16:07






      • 2





        No, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

        – michael.kebe
        May 27 '16 at 19:40








      • 2





        FYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.

        – Basil Bourque
        Jun 30 '16 at 0:33



















      Does this uses joda-time?

      – Christopher Francisco
      May 26 '16 at 16:07





      Does this uses joda-time?

      – Christopher Francisco
      May 26 '16 at 16:07




      2




      2





      No, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

      – michael.kebe
      May 27 '16 at 19:40







      No, but it developed from it. Here a quote from the joda time homepage: Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

      – michael.kebe
      May 27 '16 at 19:40






      2




      2





      FYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.

      – Basil Bourque
      Jun 30 '16 at 0:33







      FYI, the java.time classes are built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. Also, see Oracle Tutorial to learn more.

      – Basil Bourque
      Jun 30 '16 at 0:33















      52














      It's possible to do it in a much easier to read way:



      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      return d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
      // almost useless branch, could be merged with the one above
      return d;
      } else {
      return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }


      or in a bit shorter form



      private LocalDate calcNextFriday(LocalDate d) {    
      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else {
      d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }
      return d; // note that there's a possibility original object is returned
      }


      or even shorter



      private LocalDate calcNextFriday(LocalDate d) {
      if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
      d = d.plusWeeks(1);
      }
      return d.withDayOfWeek(DateTimeConstants.FRIDAY);
      }


      PS. I didn't test the actual code! :)






      share|improve this answer





















      • 2





        or compile it ... "DateTimeConstans"

        – David Victor
        Sep 14 '11 at 11:53






      • 8





        @David You saw nothing ;)

        – Esko
        Jan 23 '12 at 11:44






      • 5





        +1 for sense of humour. :)

        – David Victor
        Jan 23 '12 at 15:16











      • Your last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!

        – gyorgyabraham
        Aug 16 '13 at 15:32
















      52














      It's possible to do it in a much easier to read way:



      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      return d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
      // almost useless branch, could be merged with the one above
      return d;
      } else {
      return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }


      or in a bit shorter form



      private LocalDate calcNextFriday(LocalDate d) {    
      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else {
      d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }
      return d; // note that there's a possibility original object is returned
      }


      or even shorter



      private LocalDate calcNextFriday(LocalDate d) {
      if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
      d = d.plusWeeks(1);
      }
      return d.withDayOfWeek(DateTimeConstants.FRIDAY);
      }


      PS. I didn't test the actual code! :)






      share|improve this answer





















      • 2





        or compile it ... "DateTimeConstans"

        – David Victor
        Sep 14 '11 at 11:53






      • 8





        @David You saw nothing ;)

        – Esko
        Jan 23 '12 at 11:44






      • 5





        +1 for sense of humour. :)

        – David Victor
        Jan 23 '12 at 15:16











      • Your last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!

        – gyorgyabraham
        Aug 16 '13 at 15:32














      52












      52








      52







      It's possible to do it in a much easier to read way:



      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      return d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
      // almost useless branch, could be merged with the one above
      return d;
      } else {
      return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }


      or in a bit shorter form



      private LocalDate calcNextFriday(LocalDate d) {    
      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else {
      d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }
      return d; // note that there's a possibility original object is returned
      }


      or even shorter



      private LocalDate calcNextFriday(LocalDate d) {
      if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
      d = d.plusWeeks(1);
      }
      return d.withDayOfWeek(DateTimeConstants.FRIDAY);
      }


      PS. I didn't test the actual code! :)






      share|improve this answer















      It's possible to do it in a much easier to read way:



      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      return d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
      // almost useless branch, could be merged with the one above
      return d;
      } else {
      return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }


      or in a bit shorter form



      private LocalDate calcNextFriday(LocalDate d) {    
      if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
      d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
      } else {
      d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
      }
      return d; // note that there's a possibility original object is returned
      }


      or even shorter



      private LocalDate calcNextFriday(LocalDate d) {
      if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
      d = d.plusWeeks(1);
      }
      return d.withDayOfWeek(DateTimeConstants.FRIDAY);
      }


      PS. I didn't test the actual code! :)







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 7 '13 at 19:34









      Jason Sperske

      22.8k855107




      22.8k855107










      answered Oct 28 '09 at 9:56









      EskoEsko

      23.4k104776




      23.4k104776








      • 2





        or compile it ... "DateTimeConstans"

        – David Victor
        Sep 14 '11 at 11:53






      • 8





        @David You saw nothing ;)

        – Esko
        Jan 23 '12 at 11:44






      • 5





        +1 for sense of humour. :)

        – David Victor
        Jan 23 '12 at 15:16











      • Your last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!

        – gyorgyabraham
        Aug 16 '13 at 15:32














      • 2





        or compile it ... "DateTimeConstans"

        – David Victor
        Sep 14 '11 at 11:53






      • 8





        @David You saw nothing ;)

        – Esko
        Jan 23 '12 at 11:44






      • 5





        +1 for sense of humour. :)

        – David Victor
        Jan 23 '12 at 15:16











      • Your last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!

        – gyorgyabraham
        Aug 16 '13 at 15:32








      2




      2





      or compile it ... "DateTimeConstans"

      – David Victor
      Sep 14 '11 at 11:53





      or compile it ... "DateTimeConstans"

      – David Victor
      Sep 14 '11 at 11:53




      8




      8





      @David You saw nothing ;)

      – Esko
      Jan 23 '12 at 11:44





      @David You saw nothing ;)

      – Esko
      Jan 23 '12 at 11:44




      5




      5





      +1 for sense of humour. :)

      – David Victor
      Jan 23 '12 at 15:16





      +1 for sense of humour. :)

      – David Victor
      Jan 23 '12 at 15:16













      Your last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!

      – gyorgyabraham
      Aug 16 '13 at 15:32





      Your last snippet's "return" line contains a redundant ")" character. Anyways, thanks, great solution!

      – gyorgyabraham
      Aug 16 '13 at 15:32











      5














      Your code in 1 line



      private LocalDate calcNextFriday3(LocalDate d) {
      return d.isBefore(d.dayOfWeek().setCopy(5))?d.dayOfWeek().setCopy(5):d.plusWeeks(1).dayOfWeek().setCopy(5);
      }


      Alternative approach



      private LocalDate calcNextDay(LocalDate d, int weekday) {
      return (d.getDayOfWeek() < weekday)?d.withDayOfWeek(weekday):d.plusWeeks(1).withDayOfWeek(weekday);
      }


      private LocalDate calcNextFriday2(LocalDate d) {
      return calcNextDay(d,DateTimeConstants.FRIDAY);
      }


      somewhat tested ;-)






      share|improve this answer



















      • 1





        Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.

        – michael.kebe
        Oct 28 '09 at 10:27






      • 5





        @michaelkebe you asked for a oneliner, I just provided one... ;-)

        – fvu
        Oct 28 '09 at 10:39






      • 1





        @michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.

        – gyorgyabraham
        Aug 16 '13 at 15:51
















      5














      Your code in 1 line



      private LocalDate calcNextFriday3(LocalDate d) {
      return d.isBefore(d.dayOfWeek().setCopy(5))?d.dayOfWeek().setCopy(5):d.plusWeeks(1).dayOfWeek().setCopy(5);
      }


      Alternative approach



      private LocalDate calcNextDay(LocalDate d, int weekday) {
      return (d.getDayOfWeek() < weekday)?d.withDayOfWeek(weekday):d.plusWeeks(1).withDayOfWeek(weekday);
      }


      private LocalDate calcNextFriday2(LocalDate d) {
      return calcNextDay(d,DateTimeConstants.FRIDAY);
      }


      somewhat tested ;-)






      share|improve this answer



















      • 1





        Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.

        – michael.kebe
        Oct 28 '09 at 10:27






      • 5





        @michaelkebe you asked for a oneliner, I just provided one... ;-)

        – fvu
        Oct 28 '09 at 10:39






      • 1





        @michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.

        – gyorgyabraham
        Aug 16 '13 at 15:51














      5












      5








      5







      Your code in 1 line



      private LocalDate calcNextFriday3(LocalDate d) {
      return d.isBefore(d.dayOfWeek().setCopy(5))?d.dayOfWeek().setCopy(5):d.plusWeeks(1).dayOfWeek().setCopy(5);
      }


      Alternative approach



      private LocalDate calcNextDay(LocalDate d, int weekday) {
      return (d.getDayOfWeek() < weekday)?d.withDayOfWeek(weekday):d.plusWeeks(1).withDayOfWeek(weekday);
      }


      private LocalDate calcNextFriday2(LocalDate d) {
      return calcNextDay(d,DateTimeConstants.FRIDAY);
      }


      somewhat tested ;-)






      share|improve this answer













      Your code in 1 line



      private LocalDate calcNextFriday3(LocalDate d) {
      return d.isBefore(d.dayOfWeek().setCopy(5))?d.dayOfWeek().setCopy(5):d.plusWeeks(1).dayOfWeek().setCopy(5);
      }


      Alternative approach



      private LocalDate calcNextDay(LocalDate d, int weekday) {
      return (d.getDayOfWeek() < weekday)?d.withDayOfWeek(weekday):d.plusWeeks(1).withDayOfWeek(weekday);
      }


      private LocalDate calcNextFriday2(LocalDate d) {
      return calcNextDay(d,DateTimeConstants.FRIDAY);
      }


      somewhat tested ;-)







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Oct 28 '09 at 10:06









      fvufvu

      29k54769




      29k54769








      • 1





        Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.

        – michael.kebe
        Oct 28 '09 at 10:27






      • 5





        @michaelkebe you asked for a oneliner, I just provided one... ;-)

        – fvu
        Oct 28 '09 at 10:39






      • 1





        @michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.

        – gyorgyabraham
        Aug 16 '13 at 15:51














      • 1





        Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.

        – michael.kebe
        Oct 28 '09 at 10:27






      • 5





        @michaelkebe you asked for a oneliner, I just provided one... ;-)

        – fvu
        Oct 28 '09 at 10:39






      • 1





        @michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.

        – gyorgyabraham
        Aug 16 '13 at 15:51








      1




      1





      Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.

      – michael.kebe
      Oct 28 '09 at 10:27





      Thanks for your answer. Your suggestion with the more general approach is nice. But the oneliner is awkward in term of readability.

      – michael.kebe
      Oct 28 '09 at 10:27




      5




      5





      @michaelkebe you asked for a oneliner, I just provided one... ;-)

      – fvu
      Oct 28 '09 at 10:39





      @michaelkebe you asked for a oneliner, I just provided one... ;-)

      – fvu
      Oct 28 '09 at 10:39




      1




      1





      @michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.

      – gyorgyabraham
      Aug 16 '13 at 15:51





      @michael.kebe I usually place newlines with ternaries at "?" and ":", hit format in Eclipse and it arranges pretty well.

      – gyorgyabraham
      Aug 16 '13 at 15:51











      4














      I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.



      Anyway here is my solution:



      public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
      DateTime dt = lp.toDateTime(now);
      while (dt.isBefore(now)) {
      dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
      }
      return dt;
      }


      Now you just need to make a Partial (which LocalDate is) for the day of the week.



      Partial().with(DateTimeFieldType.dayOfWeek(), DateTimeConstants.FRIDAY); 


      Now whatever the most significant field is of the partial will be +1 if the current date is after it (now).



      That is if you make a partial with March 2012 it will create a new datetime of March 2013 or <.






      share|improve this answer






























        4














        I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.



        Anyway here is my solution:



        public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
        DateTime dt = lp.toDateTime(now);
        while (dt.isBefore(now)) {
        dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
        }
        return dt;
        }


        Now you just need to make a Partial (which LocalDate is) for the day of the week.



        Partial().with(DateTimeFieldType.dayOfWeek(), DateTimeConstants.FRIDAY); 


        Now whatever the most significant field is of the partial will be +1 if the current date is after it (now).



        That is if you make a partial with March 2012 it will create a new datetime of March 2013 or <.






        share|improve this answer




























          4












          4








          4







          I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.



          Anyway here is my solution:



          public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
          DateTime dt = lp.toDateTime(now);
          while (dt.isBefore(now)) {
          dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
          }
          return dt;
          }


          Now you just need to make a Partial (which LocalDate is) for the day of the week.



          Partial().with(DateTimeFieldType.dayOfWeek(), DateTimeConstants.FRIDAY); 


          Now whatever the most significant field is of the partial will be +1 if the current date is after it (now).



          That is if you make a partial with March 2012 it will create a new datetime of March 2013 or <.






          share|improve this answer















          I just wasted like 30 minutes trying to figure this out myself but I needed to generically roll forward.



          Anyway here is my solution:



          public static DateTime rollForwardWith(ReadableInstant now, AbstractPartial lp) {
          DateTime dt = lp.toDateTime(now);
          while (dt.isBefore(now)) {
          dt = dt.withFieldAdded(lp.getFieldTypes()[0].getRangeDurationType(), 1);
          }
          return dt;
          }


          Now you just need to make a Partial (which LocalDate is) for the day of the week.



          Partial().with(DateTimeFieldType.dayOfWeek(), DateTimeConstants.FRIDAY); 


          Now whatever the most significant field is of the partial will be +1 if the current date is after it (now).



          That is if you make a partial with March 2012 it will create a new datetime of March 2013 or <.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 18 '12 at 3:13

























          answered Jul 18 '12 at 3:01









          Adam GentAdam Gent

          34.6k19125167




          34.6k19125167























              4














              import java.util.Calendar;

              private Calendar getNextweekOfDay(int weekOfDay) {
              Calendar today = Calendar.getInstance();
              int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
              int daysUntilNextWeekOfDay = weekOfDay - dayOfWeek;
              if (daysUntilNextWeekOfDay == 0) daysUntilNextWeekOfDay = 7;
              Calendar nextWeekOfDay = (Calendar)today.clone();
              nextWeekOfDay.add(Calendar.DAY_OF_WEEK, daysUntilNextWeekOfDay);
              return nextWeekOfDay;
              }

              // set alarm for next Friday 9am
              public void setAlarm() {
              Calendar calAlarm = getNextweekOfDay(Calendar.FRIDAY);
              calAlarm.set(Calendar.HOUR_OF_DAY, 9);//9am
              calAlarm.set(Calendar.MINUTE, 0);
              calAlarm.set(Calendar.SECOND, 0);
              scheduleAlarm(calAlarm);// this is my own method to schedule a pendingIntent
              }





              share|improve this answer


























              • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                – Basil Bourque
                Nov 30 '18 at 1:15
















              4














              import java.util.Calendar;

              private Calendar getNextweekOfDay(int weekOfDay) {
              Calendar today = Calendar.getInstance();
              int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
              int daysUntilNextWeekOfDay = weekOfDay - dayOfWeek;
              if (daysUntilNextWeekOfDay == 0) daysUntilNextWeekOfDay = 7;
              Calendar nextWeekOfDay = (Calendar)today.clone();
              nextWeekOfDay.add(Calendar.DAY_OF_WEEK, daysUntilNextWeekOfDay);
              return nextWeekOfDay;
              }

              // set alarm for next Friday 9am
              public void setAlarm() {
              Calendar calAlarm = getNextweekOfDay(Calendar.FRIDAY);
              calAlarm.set(Calendar.HOUR_OF_DAY, 9);//9am
              calAlarm.set(Calendar.MINUTE, 0);
              calAlarm.set(Calendar.SECOND, 0);
              scheduleAlarm(calAlarm);// this is my own method to schedule a pendingIntent
              }





              share|improve this answer


























              • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                – Basil Bourque
                Nov 30 '18 at 1:15














              4












              4








              4







              import java.util.Calendar;

              private Calendar getNextweekOfDay(int weekOfDay) {
              Calendar today = Calendar.getInstance();
              int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
              int daysUntilNextWeekOfDay = weekOfDay - dayOfWeek;
              if (daysUntilNextWeekOfDay == 0) daysUntilNextWeekOfDay = 7;
              Calendar nextWeekOfDay = (Calendar)today.clone();
              nextWeekOfDay.add(Calendar.DAY_OF_WEEK, daysUntilNextWeekOfDay);
              return nextWeekOfDay;
              }

              // set alarm for next Friday 9am
              public void setAlarm() {
              Calendar calAlarm = getNextweekOfDay(Calendar.FRIDAY);
              calAlarm.set(Calendar.HOUR_OF_DAY, 9);//9am
              calAlarm.set(Calendar.MINUTE, 0);
              calAlarm.set(Calendar.SECOND, 0);
              scheduleAlarm(calAlarm);// this is my own method to schedule a pendingIntent
              }





              share|improve this answer















              import java.util.Calendar;

              private Calendar getNextweekOfDay(int weekOfDay) {
              Calendar today = Calendar.getInstance();
              int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
              int daysUntilNextWeekOfDay = weekOfDay - dayOfWeek;
              if (daysUntilNextWeekOfDay == 0) daysUntilNextWeekOfDay = 7;
              Calendar nextWeekOfDay = (Calendar)today.clone();
              nextWeekOfDay.add(Calendar.DAY_OF_WEEK, daysUntilNextWeekOfDay);
              return nextWeekOfDay;
              }

              // set alarm for next Friday 9am
              public void setAlarm() {
              Calendar calAlarm = getNextweekOfDay(Calendar.FRIDAY);
              calAlarm.set(Calendar.HOUR_OF_DAY, 9);//9am
              calAlarm.set(Calendar.MINUTE, 0);
              calAlarm.set(Calendar.SECOND, 0);
              scheduleAlarm(calAlarm);// this is my own method to schedule a pendingIntent
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 24 '18 at 16:55









              Someone Somewhere

              18.8k1096140




              18.8k1096140










              answered Jun 16 '15 at 7:19









              dinesh pazanidinesh pazani

              487




              487













              • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                – Basil Bourque
                Nov 30 '18 at 1:15



















              • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                – Basil Bourque
                Nov 30 '18 at 1:15

















              FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

              – Basil Bourque
              Nov 30 '18 at 1:15





              FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

              – Basil Bourque
              Nov 30 '18 at 1:15











              3














              counting bytes @fvu answer can be shortened even further to:



              private LocalDate calcNextFriday(LocalDate d) {
              return d.plusWeeks(d.getDayOfWeek() < DateTimeConstants.FRIDAY ? 0 : 1).withDayOfWeek(DateTimeConstants.FRIDAY);
              }





              share|improve this answer




























                3














                counting bytes @fvu answer can be shortened even further to:



                private LocalDate calcNextFriday(LocalDate d) {
                return d.plusWeeks(d.getDayOfWeek() < DateTimeConstants.FRIDAY ? 0 : 1).withDayOfWeek(DateTimeConstants.FRIDAY);
                }





                share|improve this answer


























                  3












                  3








                  3







                  counting bytes @fvu answer can be shortened even further to:



                  private LocalDate calcNextFriday(LocalDate d) {
                  return d.plusWeeks(d.getDayOfWeek() < DateTimeConstants.FRIDAY ? 0 : 1).withDayOfWeek(DateTimeConstants.FRIDAY);
                  }





                  share|improve this answer













                  counting bytes @fvu answer can be shortened even further to:



                  private LocalDate calcNextFriday(LocalDate d) {
                  return d.plusWeeks(d.getDayOfWeek() < DateTimeConstants.FRIDAY ? 0 : 1).withDayOfWeek(DateTimeConstants.FRIDAY);
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 6 '14 at 10:18









                  Stefan HaberlStefan Haberl

                  4,17333951




                  4,17333951























                      0














                      A simple modulo based solution which should work with most of former java versions in case you are not allowed to upgrade your java version to java8 or onwards or to use a standard java date library as jodatime



                      Number of days to add to your date is given by this formula :



                      (7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7



                      Note also this can be generalized for any week day by changing the static field Calendar.FRIDAY to your given weekday. Some snippet code below



                      public static void main(String args) {
                      for (int i = 0; i < 15; i++) {

                      Calendar cur = Calendar.getInstance();
                      cur.add(Calendar.DAY_OF_MONTH, i);

                      Calendar friday = Calendar.getInstance();
                      friday.setTime(cur.getTime());
                      friday.add(Calendar.DAY_OF_MONTH, (7 + Calendar.FRIDAY - cur.get(Calendar.DAY_OF_WEEK)) % 7);

                      System.out.println(MessageFormat.format("Date {0} -> {1} ", cur.getTime(), friday.getTime()));
                      }
                      }





                      share|improve this answer


























                      • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                        – Basil Bourque
                        Nov 30 '18 at 1:14











                      • Yes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.

                        – Breton F.
                        Dec 7 '18 at 15:26
















                      0














                      A simple modulo based solution which should work with most of former java versions in case you are not allowed to upgrade your java version to java8 or onwards or to use a standard java date library as jodatime



                      Number of days to add to your date is given by this formula :



                      (7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7



                      Note also this can be generalized for any week day by changing the static field Calendar.FRIDAY to your given weekday. Some snippet code below



                      public static void main(String args) {
                      for (int i = 0; i < 15; i++) {

                      Calendar cur = Calendar.getInstance();
                      cur.add(Calendar.DAY_OF_MONTH, i);

                      Calendar friday = Calendar.getInstance();
                      friday.setTime(cur.getTime());
                      friday.add(Calendar.DAY_OF_MONTH, (7 + Calendar.FRIDAY - cur.get(Calendar.DAY_OF_WEEK)) % 7);

                      System.out.println(MessageFormat.format("Date {0} -> {1} ", cur.getTime(), friday.getTime()));
                      }
                      }





                      share|improve this answer


























                      • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                        – Basil Bourque
                        Nov 30 '18 at 1:14











                      • Yes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.

                        – Breton F.
                        Dec 7 '18 at 15:26














                      0












                      0








                      0







                      A simple modulo based solution which should work with most of former java versions in case you are not allowed to upgrade your java version to java8 or onwards or to use a standard java date library as jodatime



                      Number of days to add to your date is given by this formula :



                      (7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7



                      Note also this can be generalized for any week day by changing the static field Calendar.FRIDAY to your given weekday. Some snippet code below



                      public static void main(String args) {
                      for (int i = 0; i < 15; i++) {

                      Calendar cur = Calendar.getInstance();
                      cur.add(Calendar.DAY_OF_MONTH, i);

                      Calendar friday = Calendar.getInstance();
                      friday.setTime(cur.getTime());
                      friday.add(Calendar.DAY_OF_MONTH, (7 + Calendar.FRIDAY - cur.get(Calendar.DAY_OF_WEEK)) % 7);

                      System.out.println(MessageFormat.format("Date {0} -> {1} ", cur.getTime(), friday.getTime()));
                      }
                      }





                      share|improve this answer















                      A simple modulo based solution which should work with most of former java versions in case you are not allowed to upgrade your java version to java8 or onwards or to use a standard java date library as jodatime



                      Number of days to add to your date is given by this formula :



                      (7 + Calendar.FRIDAY - yourDateAsCalendar.get(Calendar.DAY_OF_WEEK)) % 7



                      Note also this can be generalized for any week day by changing the static field Calendar.FRIDAY to your given weekday. Some snippet code below



                      public static void main(String args) {
                      for (int i = 0; i < 15; i++) {

                      Calendar cur = Calendar.getInstance();
                      cur.add(Calendar.DAY_OF_MONTH, i);

                      Calendar friday = Calendar.getInstance();
                      friday.setTime(cur.getTime());
                      friday.add(Calendar.DAY_OF_MONTH, (7 + Calendar.FRIDAY - cur.get(Calendar.DAY_OF_WEEK)) % 7);

                      System.out.println(MessageFormat.format("Date {0} -> {1} ", cur.getTime(), friday.getTime()));
                      }
                      }






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Dec 7 '18 at 15:27

























                      answered Nov 22 '18 at 1:39









                      Breton F.Breton F.

                      896




                      896













                      • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                        – Basil Bourque
                        Nov 30 '18 at 1:14











                      • Yes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.

                        – Breton F.
                        Dec 7 '18 at 15:26



















                      • FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                        – Basil Bourque
                        Nov 30 '18 at 1:14











                      • Yes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.

                        – Breton F.
                        Dec 7 '18 at 15:26

















                      FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                      – Basil Bourque
                      Nov 30 '18 at 1:14





                      FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

                      – Basil Bourque
                      Nov 30 '18 at 1:14













                      Yes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.

                      – Breton F.
                      Dec 7 '18 at 15:26





                      Yes If you use java 8 or onwards version or Jodatime, this is not for you. I did say it but i was not clear. Thanks for commenting.

                      – Breton F.
                      Dec 7 '18 at 15:26


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1636038%2ftime-how-to-get-the-next-friday%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith