简体   繁体   中英

Get Last Day (Date) of Week for a given Date

How to get the last week Day (saturday) Date for a particular Date. Means if I give Input as 06-04-2012

(MM-dd-YYYY)

The output should be 06-09-2012 as seen in this calendar .

Calendar cal  = Calendar.getInstance();
int currentDay = cal.get(Calendar.DAY_OF_WEEK);
int leftDays= Calendar.SATURDAY - currentDay;
cal.add(Calendar.DATE, leftDays);

See

tl;dr

LocalDate.parse( 
    "06-04-2012" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) 
).with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) )
 .format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" )  )

Using java.time

The modern way is with java.time classes.

First parse your input string as a LocalDate .

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
LocalDate ld = LocalDate.parse( "06-04-2012" , f );

ld.toString(): 2012-06-04

Then get the next Saturday, or use the date itself if it is a Saturday. To specify a Saturday, use the enum DayOfWeek.SATURDAY . To find that next or same date that is a Saturday, use an implementation of TemporaAdjuster found in the TemporalAdjusters (note plural name) class.

LocalDate nextOrSameSaturday = 
    ld.with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) ) ;

To generate a String, I suggest calling toString to use standard ISO 8601 format.

String output = ld.toString();

2012-06-09

But if you insist, you may use the same formatter as used in parsing.

String output = ld.format( f );

06-09-2012


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

查看JODA时间或(如果无法添加新库)Calendar类。

public Calendar lastDayOfWeek(Calendar calendar){  
     Calendar cal = (Calendar) calendar.clone();  
     int day = cal.get(Calendar.DAY_OF_YEAR);  
     while(cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY){  
          cal.set(Calendar.DAY_OF_YEAR, ++day);  
     }  
     return cal;  
}  

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