5

I have a date and I need to know the last week and last month before the date.

For example,

on July 15, 2018, Its last week was from July 2 to July 8. Its last month was June 1 to June 30.

on July 16, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.

on July 17, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.

It is different from get-date-of-first-day-of-week-based-on-localdate-now-in-java-8, my problem is to get last week or last month.

dai
  • 1,025
  • 2
  • 13
  • 33
  • 2
    What have you actually tried? Which part have you been stuck on? – Rob Audenaerde Jul 16 '18 at 07:12
  • @RobAu Sorry, I don't have any ideas. – dai Jul 16 '18 at 07:16
  • Possible duplicate of [Get date of first day of week based on LocalDate.now() in Java 8](https://stackoverflow.com/questions/28450720/get-date-of-first-day-of-week-based-on-localdate-now-in-java-8) – azro Jul 16 '18 at 07:26
  • @Frank.Dai you may have tried to look for answer, yet i found 2 on SO, https://stackoverflow.com/questions/2937086/how-to-get-the-first-day-of-the-current-week-and-month – azro Jul 16 '18 at 07:26
  • I did some edits to my answer, now it fits your question, check if it's ok – Leviand Jul 16 '18 at 07:44
  • I'm curious. What is the definition of a date's "last week"? Is it a seven-days period that ended the day before the given date (not caring if it is a Monday, Sunday, Friday and so on)? Is it a Monday to Sunday period, the last that occurred entirely before the given date (even if the given date is a Sunday and therefore that makes its last week end 7 days ago)? – kumesana Jul 16 '18 at 08:12
  • @Frank.Dai your edit says _my problem is to get last week or last month_ , which is exactly what I've posted in the answer: why is not a good answer? – Leviand Jul 16 '18 at 08:13
  • @kumesana I added two more examples. – dai Jul 16 '18 at 08:47
  • @Frank.Dai look my edit in answer. That's exactly what my answer does. – Leviand Jul 16 '18 at 09:05
  • @Frank.Dai There is 3 answers that match your requirement, comment them if something is missing, or consider to accept one. – azro Jul 16 '18 at 15:31

4 Answers4

11

You can use these helper methods.

public static LocalDate[] getPreviousWeek(LocalDate date) {
    final int dayOfWeek = date.getDayOfWeek().getValue();
    final LocalDate from = date.minusDays(dayOfWeek + 6); // (dayOfWeek - 1) + 7
    final LocalDate to = date.minusDays(dayOfWeek);

    return new LocalDate[]{from, to};
}

public static LocalDate[] getPreviousMonth(LocalDate date) {
    final LocalDate from = date.minusDays(date.getDayOfMonth() - 1).minusMonths(1);
    final LocalDate to = from.plusMonths(1).minusDays(1);

    return new LocalDate[]{from, to};
}

There are in fact many ways to write this. I would suggest you to do some exploration on your own.

Jai
  • 8,165
  • 2
  • 21
  • 52
4

You can easly do that with Java 8 LocalDate, here's my solution:

import java.time.LocalDate;

LocalDate now = LocalDate.now();
LocalDate weekStart = now.minusDays(7+now.getDayOfWeek().getValue()-1);
LocalDate weekEnd = now.minusDays(now.getDayOfWeek().getValue());

LocalDate previousMonth = now.minusMonths(1);
LocalDate monthStart = previousMonth.withDayOfMonth(1);
LocalDate monthEnd = previousMonth.withDayOfMonth(previousMonth.getMonth().maxLength());

System.out.println("WeekStart:"+weekStart+", weekEnd:"+weekEnd+", monthStart:"+monthStart+", monthEnd:"+monthEnd);

Result

WeekStart:2018-07-09, weekEnd:2018-07-15, monthStart:2018-06-01, monthEnd:2018-06-30

If you change the now line with

LocalDate now = LocalDate.of(2018,07,15);

You'll get:

WeekStart:2018-07-02, weekEnd:2018-07-08, monthStart:2018-06-01, monthEnd:2018-06-30

Leviand
  • 2,745
  • 4
  • 29
  • 43
1

ZonedDateTime is useful for that.

import java.time.*;
import java.time.format.DateTimeFormatter;

class DateTest
{
    public static void main (String[] args) throws java.lang.Exception
    {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("dd MMM yyyy");
        ZoneId usCentral = ZoneId.of("America/Chicago");
        LocalDateTime localDateTime = LocalDateTime.of(2018, Month.JULY, 16, 9, 30);

        ZonedDateTime input = ZonedDateTime.of(localDateTime, usCentral);
        System.out.println("Input date = " + format.format(input));

        ZonedDateTime startDate = input.minusWeeks(1).with(DayOfWeek.MONDAY);
        System.out.println("Start date = " + format.format(startDate));

        ZonedDateTime endDate = startDate.plusDays(6);
        System.out.println("End date = " + format.format(endDate));
    }
}

Output:

Input date = 16 Jul 2018
Start date = 09 Jul 2018
End date = 15 Jul 2018
  • 2
    I'd say LocalDate is even more useful, concentrating on only what you need and avoiding a lot of stuff you don't. – kumesana Jul 16 '18 at 08:09
0

Not sure if you got a Date object, hopefully you got. From date object you can get Instant with method toInstant() (To pasrse String to date..

DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);

date format must be addapted to your needs ofcourse )

Instant.now().minus(Duration.ofDays(7))); // last week
Instant.now().minus(Duration.of(1,ChronoUnit.MONTHS)) // last month
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Alexandros
  • 733
  • 2
  • 10
  • 24
  • 2
    the old Java Date API should not be used – Lino Jul 16 '18 at 07:36
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jul 16 '18 at 08:22
  • 1
    Thanks for also trying to use *java.time*. However your last line throws `java.time.temporal.UnsupportedTemporalTypeException: Unit must not have an estimated duration`. – Ole V.V. Jul 16 '18 at 08:23