Rhys
Rhys

Reputation: 2877

Last week date from Date()

AIM: I would like to get the last day of the week (Sunday) for the next 12 weeks into seperate Strings using Date()

I have the below which gives me the correct date format. I just need suggestions on the best solution to achieve my goal.

    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date date = new Date(0);
    System.out.println(dateFormat.format(date)); 

Upvotes: 1

Views: 598

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 340118

tl;dr

LocalDate.now( 
    ZoneId.of( "Africa/Tunis" ) 
)
.withNextOrSame( DayOfWeek.SUNDAY )
.plusWeeks( 1 ) 

java.time

The modern approach uses the java.time classes.

Today

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate today = LocalDate.now( z );

Day of week

To find the next Sunday on or after today, use a TemporalAdjuster implementation found in the TemporalAdjusters class.

LocalDate nextOrSameSunday = today.withNextOrSame( DayOfWeek.SUNDAY ) ;

Collection

Collect a dozen such sequential dates.

int countWeeks = 12 ;
List< LocalDate > sundays = new ArrayList<>( 12 ) ;
for( int i = 0 , i < countWeeks , i ++ ) {
    sundays.add( nextOrSameSunday.plusWeeks( i ) ) ;  // + 0, + 1, + 2, … , + 11.
}

Tip: Focus on working with representative data objects rather than mere Strings. When needed for display, loop your collection and generate strings with a call to toString or format( DateTimeFormatter ).

for( LocalDate ld : sundays ) {      // Loop each LocalDate in collection.
    String output = ld.toString() ;  // Generate a string in standard ISO 8601 format.
    …
}

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.

Upvotes: 1

habsq
habsq

Reputation: 1832

Firstly, the last of the week is not always the same as Sunday since it is depending on which Locale you are using.

If you are using Java 8, the solution is pretty straightforward:

LocalDate firstJanuary = LocalDate.parse("01/01/2015",
                           DateTimeFormatter.ofPattern("MM/dd/yyyy"));

//last day of the week
TemporalField fieldUS = WeekFields.of(Locale.US).dayOfWeek();
LocalDate lastDayOfWeek = firstJanuary.with(fieldUS,7);
System.out.println(lastDayOfWeek);

//sunday
LocalDate sunday = firstJanuary.with(DayOfWeek.SUNDAY);
System.out.println(sunday);

and to iterate to the weeks after, simply use:

sunday.plusWeeks(1);

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

try

    GregorianCalendar c = new GregorianCalendar();
    for (int i = 0; i < 12;) {
        c.add(Calendar.DATE, 1);
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            System.out.println(DateFormat.getDateInstance().format(c.getTime()));
            i++;
        }
    }

Upvotes: 1

Patashu
Patashu

Reputation: 21793

Java's date system baffles me, but I think you want to do this:

1) Instead of making a Date, make a GregorianCalendar.

2) Calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY) to get the date for the sunday of this week.

3) In a for loop, add 7 days to the calendar twelve times. Do something on each loop (For instance, use getTime() to get a Date from the GregorianCalendar)

Upvotes: 1

Related Questions