How to get last week and last month with java8 - java

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.

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.

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

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

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

Related

Unable to parse a Month+day using DateTimeFormatter

I tried looking at this link for inspiration: Parsing a date’s ordinal indicator ( st, nd, rd, th ) in a date-time string
However I am getting an error when I try to parse a string "Mon 21st May" to "Monday 21st May" - full day name, date number and full month.
Exception in thread "main" java.time.format.DateTimeParseException:
Text 'Mon 21st May' could not be parsed at index 0 at
java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400) at
HelloWorld.main(HelloWorld.java:45)
Here is the code:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args) throws Exception
{
String str = "Mon 21st May";
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("EEEE d['st']['nd']['rd']['th'] MMMM", Locale.ENGLISH);
LocalDate datetext = LocalDate.parse(str, parseFormatter);
}
}
UPDATE:
Here is the latest code I have tried following suggestions and I changed the string to see if the issue is with that and below is there error I now receive. Looks like it knows the dates, just not able to parse it:
public static void main(String[] args) throws Exception
{
String str = "Tue 21st May";
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("EEE d['st']['nd']['rd']['th'] MMMM", Locale.ENGLISH);
LocalDate datetext = LocalDate.parse(str, parseFormatter);
}
}
Error:
Exception in thread "main" java.time.format.DateTimeParseException:
Text 'Tue 21st May' could not be parsed: Unable to obtain LocalDate from
TemporalAccessor: {DayOfWeek=2, DayOfMonth=21, MonthOfYear=5},ISO of
type java.time.format.Parsed at
java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDate.parse(LocalDate.java:400) at
HelloWorld.main(HelloWorld.java:26) Caused by:
java.time.DateTimeException: Unable to obtain LocalDate from
TemporalAccessor: {DayOfWeek=2, DayOfMonth=21, MonthOfYear=5},ISO of
type java.time.format.Parsed at
java.time.LocalDate.from(LocalDate.java:368) at
java.time.format.Parsed.query(Parsed.java:226) at
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 2 more
MonthDay
If you want to parse month and day of month without a year, use MonthDay:
String str = "Mon 21st May";
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("EEE d['st']['nd']['rd']['th'] MMMM", Locale.ENGLISH);
MonthDay md = MonthDay.parse(str, parseFormatter);
System.out.println(md);
Output is:
--05-21
The leading dash indicates an absent year. EEEE in the format pattern string is for full name of the day of week, like Monday or Tuesday. For the abbreviation you need either E, EE or EEE.
LocalDate
If you want a LocalDate, you need to supply a year somehow. One option is:
LocalDate datetext = md.atYear(Year.now(ZoneId.of("Europe/London")).getValue());
System.out.println(datetext);
2019-05-21
This doesn’t validate the day of month, though. To do that:
String str = "Tue 21st May";
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.appendPattern("EEE d['st']['nd']['rd']['th'] MMMM")
.parseDefaulting(ChronoField.YEAR, Year.now(ZoneId.of("Europe/London")).getValue())
.toFormatter(Locale.ENGLISH);
LocalDate datetext = LocalDate.parse(str, parseFormatter);
2019-05-21
In the comment you asked:
What about if I want to output it as Tuesday 21 May?
It’s sort of a new question and has been covered many times, but OK.
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.ENGLISH);
System.out.println(datetext.format(outputFormatter));
Tuesday 21 May
Detecting year from day of week
I may not know the year, as in I am trying to view dates in an
application but some dates may be this year, some may fall over to
next year but these dates don't have a year supplied
The following complete example assumes the date falls within the next 3 years from today and detects the year where the day of week is correct. On success it prints in your desired format.
String str = "Wed 20th May";
ZoneId zone = ZoneId.of("Europe/London");
LocalDate today = LocalDate.now(zone);
int currentYear = today.getYear();
LocalDate datetext = null;
final int maxYearsFromToday = 3;
for (int year = currentYear; year <= currentYear + maxYearsFromToday; year++) {
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.appendPattern("EEE d['st']['nd']['rd']['th'] MMMM")
.parseDefaulting(ChronoField.YEAR, year)
.toFormatter(Locale.ENGLISH);
try {
datetext = LocalDate.parse(str, parseFormatter);
System.out.println("Day of week matched for year " + year);
break;
} catch (DateTimeParseException dtpe) {
// Ignore, try next year
}
}
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.ENGLISH);
if (datetext == null) {
System.out.println("Could not parse date;"
+ " possibly the day of week didn’t match for any year in the range "
+ currentYear + " through " + (currentYear + maxYearsFromToday));
} else if (datetext.isBefore(today) || datetext.isAfter(today.plusYears(maxYearsFromToday))) {
System.out.println("Date is out of range");
} else {
System.out.println("Successfully parsed: " + datetext.format(outputFormatter));
}
Day of week matched for year 2020
Successfully parsed: Wednesday 20 May
It's Tuesday 21st May 2019. The code below works.
String str = "Tue 21st May 2019";
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("EEE d['st']['nd']['rd']['th'] MMMM yyyy", Locale.ENGLISH);
LocalDate datetext = LocalDate.parse(str, parseFormatter);
Here is my code to search for correct year:
Without knowing the day-name of the week, you have a 6/7 chance of parsing the date into the incorrect year. BUT, if you know the day-name, then you can search a 7 year range to find the correct year.
Assuming you have either a date like one of the following:
Wednesday, May 27
WED 5/27
And formatters like:
DateTimeFormatter visibleButtonFormat = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("EEE M/dd")
.toFormatter(Locale.US);
DateTimeFormatter accessibleFormat = DateTimeFormatter.ofPattern("EEEE, MMMM dd");
Then, you can parse a MonthDay like so:
MonthDay monthDay = MonthDay.parse(dateText, oneOfTheAboveFormatters);
Then, you can search for the correct year. In this case it is 2020:
private static int findYearMatchingMonthDay(String dateText, MonthDay monthDay) {
for(int checkYear = 2020; checkYear >= 2016; checkYear--) {
LocalDate localDate = LocalDate.of(checkYear, monthDay.getMonth(), monthDay.getDayOfMonth());
String shortDay = localDate.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US).toUpperCase();
if (shortDay.equals(dateText.substring(0,3))) {
ConsoleUtils.logDebug("Assuming schedule buttons within year: " + checkYear);
return checkYear;
}
}
return Year.now().getValue();
}

How to select sunday before first monday of the passed month

I want to select Sunday before first Monday of the passed month.
That Sunday may be in the same month or the previous month but I want date of Sunday. I tried below logic for getting Sunday, it works for the current month but if I try passing some another month like Nov-2017 then again I have to change MONDAY-2 to MONDAY-3. So this is not the correct way. So how can I achieve this ?
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY - 2);
System.out.println("Date " + c.getTime());
I want to pass date to the code. So how can i do it ? like if I have date saved in variable then according to the input provided by that variable it should calculate the logic and provide the output
#Test
public void testDate() throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
Date d = fmt.parse("01-Nov-2017");
System.out.println(d);
Calendar c = Calendar.getInstance();
c.setTime(d);
getSundayBefore1thMondayOfMonth(c);
}
public void getSundayBefore1thMondayOfMonth(Calendar c) {
c.set(Calendar.DAY_OF_MONTH, 1);
int wd = c.get(Calendar.DAY_OF_WEEK);
if (wd > Calendar.MONDAY ) {
c.add(Calendar.DAY_OF_MONTH, 7);
}
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(c.getTime());
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(c.getTime());
}
Wed Nov 01 00:00:00 CST 2017
Mon Nov 06 00:00:00 CST 2017
Sun Nov 05 00:00:00 CST 2017
If you are using Java 8, Then you can use java.time library and you can just use :
LocalDate firstMondayOfMonth = LocalDate.now().with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2018-01-01
LocalDate sunday = firstMondayOfMonth.minusDays(1);//This return 2017-12-31
To test with November 2017 you can use LocalDate.of instead LocalDate.now() like this :
LocalDate firstMondayOfMonth = LocalDate.of(2017, Month.NOVEMBER, 1).with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2017-11-06
LocalDate firstSunday = firstMondayOfMonth.minusDays(1);// This return 2017-11-05
tl;dr
YearMonth
.now() // Current year-month. Tip: Better to pass the optional time zone, as shown further down in this Answer.
.atDay( 1 ) // First of the current month.
.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) // Move from first day of month to the following Monday, or stay on the first if it already a Monday.
.minusDays( 1 ) // Move back one day from Monday to get a Sunday. May be in current month or in previous month.
java.time
You are using troublesome old date-date classes that are now legacy, supplanted by the java.time classes.
Determining the current month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
The YearMonth class represent the entire month.
YearMonth currentYearMonth = YearMonth.now( z ) ;
From that we can get the first of the month.
LocalDate firstOfMonth = currentYearMonth.atDay( 1 ) ;
We can move to a certain day of the week by calling on a TemporalAdjuster.
LocalDate firstMondayOfMonth = firstOfMonth.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) ;
LocalDate sundayBeforeFirstMondayOfMonth = firstMondayOfMonth.with( TemporalAdjusters.previous( DayOfWeek.SUNDAY ) ) ;
Logically, that last line could be replaced with .minusDays( 1 ) as we know the previous Sunday immediately precedes our Monday by definition.
In the code below, first we get the first monday in the month. Then we just subtract 1 day.
// input
int year = 2017;
int month = Calendar.NOVEMBER;
// get first monday of the month
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
System.out.println("Date " + c.getTime());
// subtract 1
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println("Date " + c.getTime());
Try this:
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
calendar.add(Calendar.DATE, -1);
System.out.println(calendar.getTime());
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek( Calendar.MONDAY); //Monday is first day of a week
c.setMinimalDaysInFirstWeek( 1); //first week of month is the week that has at least one day in this month
//c.setMinimalDaysInFirstWeek( 7); //first week of month must be a full week
c.set(Calendar.WEEK_OF_MONTH, 1); //move to first week of month
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //move to Monday
System.out.println("Date " + c.getTime());
c.add( Calendar.DAY_OF_MONTH, -1); //go back one day
System.out.println("Date " + c.getTime());
Choose one of the c.setMinimalDaysInFirstWeek() method depending on what the first week of month means to you.
In Java 8, you can use the below code:
public static void getSundayBeforeFirstMondayOfMonth(LocalDate date){
date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)).minusDays(1);
}
And, call the above method like below as per the requirement:
public static void callerMethod(){
// Call with Current Date
getSundayBeforeFirstMondayOfMonth(LocalDate.now());
//Call with Custom Date
LocalDate customDate = LocalDate.parse("27-11-2017", DateTimeFormatter.ofPattern("DD-MM-YYYY"));
getSundayBeforeFirstMondayOfMonth(customDate);
}

Calendar Sunday to Sunday

I'm trying to get flights for 8 days starting from Sunday to the next Sunday.
The way I have implemented it now is by displaying the 7 days starting the selected date from my form.
// set up calendar for sunday
Calendar sunday = Calendar.getInstance();
sunday.setTime(form.getDate());
sunday.add(Calendar.DAY_OF_WEEK, -1 * (sunday.get(Calendar.DAY_OF_WEEK) - 1));
//set up calendar for next saturday
Calendar saturday = Calendar.getInstance();
saturday.setTime(sunday.getTime());
saturday.add(Calendar.DAY_OF_WEEK, 7);
Since the max of DAY_OF_WEEK is 7, what do I need to use instead?
I tried changing this line:
saturday.add(Calendar.DAY_OF_WEEK, 7);
to the following one:
saturday.add(Calendar.DATE, 8);
I already tried couple changes but no luck.
Any advice?
Try using Calendar.DAY_OF_YEAR.
import java.text.*;
import java.util.*;
DateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy hh:mm:ss a z");
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Set day of week to Sunday.
System.out.println(dateFormat.format(sunday.getTime()));
sunday.add(Calendar.DAY_OF_YEAR, 7); // Add seven days.
System.out.println(dateFormat.format(sunday.getTime()));
Output
Sun, Dec 04, 2016 11:47:32 PM EST
Sun, Dec 11, 2016 11:47:32 PM EST
You can create new calendar objects without modifying the existing one, by making a copy.
import java.text.*;
import java.util.*;
public class CalendarUtils {
public static void main(String[] args) {
Calendar sunday = CalendarUtils.getThisSundaysDate();
Calendar saturday = CalendarUtils.daysFrom(sunday, 6);
CalendarUtils.printDates(sunday, saturday);
}
public static Calendar getThisSundaysDate() {
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return sunday;
}
public static Calendar daysFrom(Calendar cal, int days) {
Calendar newCal = copyCalendar(cal);
newCal.add(Calendar.DAY_OF_YEAR, days);
return newCal;
}
public static Calendar copyCalendar(Calendar cal) {
Calendar copy = new GregorianCalendar();
copy.setTime(cal.getTime());
return copy;
}
public static void printDates(Calendar from, Calendar to) {
DateFormat dateFormat = new SimpleDateFormat("EEE, MMMM dd, yyyy hh:mm:ss a z");
System.out.println(dateFormat.format(from.getTime()));
System.out.println(dateFormat.format(to.getTime()));
}
}
If you're using Java 8, you should use the new java.time classes. In this case, you'd want to use the LocalDate class, and the TemporalAdjusters class, with it's previous(DayOfWeek) method.
Alternatively, use the previousOrSame(DayOfWeek), depending on what should happen if the reference date is a Sunday.
Example, using today as the reference date:
LocalDate refDate = LocalDate.now();
LocalDate prevSunday = refDate.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
LocalDate nextSunday = prevSunday.plusDays(7);
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
System.out.println("Ref. Date: " + refDate.format(fmt));
System.out.println("Prev. Sunday: " + prevSunday.format(fmt));
System.out.println("Next. Sunday: " + nextSunday.format(fmt));
Output
Ref. Date: Monday, December 5, 2016
Prev. Sunday: Sunday, December 4, 2016
Next. Sunday: Sunday, December 11, 2016

Convert month name to Date range

I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.
Examples
getDateRange("Feb",2015)
should find the range 2015-02-01 -- 2015-02-28
While
getDateRange("Feb",2016)
should find the range 2016-02-01 -- 2016-02-29
In Java 8, you can do that using TemporalAdjusters,
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.
YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
int monthLen= ym.lengthOfMonth();
Java 8 made Date-Time operations very simple.
For Java 7 and below you could get away with something like this;
void getDate(String month, int year) throws ParseException {
Date start = null, end = null;
//init month and year
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
Date parse = sdf.parse(month);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
instance.set(Calendar.YEAR, year);
//start is default first day of month
start = instance.getTime();
//calculate end
instance.add(Calendar.MONTH, 1);
instance.add(Calendar.DAY_OF_MONTH, -1);
end = instance.getTime();
System.out.println(start + " " + end);
}
The output would be for "Feb", 2015:
Sun Feb 01 00:00:00 EET 2015
Sat Feb 28 00:00:00 EET 2015
Java 7 solution with default Java tools:
public static void getDateRange(String shortMonth, int year) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
// the parsed date will be the first day of the given month and year
Date startDate = format.parse(shortMonth + " " + year);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// set calendar to the last day of this given month
calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
// and get a Date object
Date endDate = calendar.getTime();
// do whatever you need to do with your dates, return them in a Pair or print out
System.out.println(startDate);
System.out.println(endDate);
}
Try (untested):
public List<LocalDate> getDateRange(YearMonth yearMonth){
List<LocalDate> dateRange = new ArrayList<>();
IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
return dateRange
}
Java 8 provides new date API as Masud mentioned.
However if you are not working under a Java 8 environment, then lamma date is a good option.
// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create
Date fromDt = new Date(2014, 2, 1);
// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();

How to compare two dates created as JodaTime LocalDate and LocalDateTime?

LocalDate startDate = new LocalDate(2014,1,2);
LocalDateTime startDateTime = new LocalDateTime(2014,1,2,14,0);
I need to compare startDate and startDateTime with respect to the date, something like this:
// boolean equalDates = startDate.isequal(startDateTime.getDate());
Is it possible to do this?
If you just want to compare the date part, you can do it like so:
LocalDate startDate = new LocalDate(2014, 1, 2);
LocalDateTime startDateTime = new LocalDateTime(2014, 1, 2, 14, 0);
LocalDate forCompare = startDateTime.toLocalDate();
System.out.println("equal dates: " + forCompare.equals(startDate));
// equal dates: true
docs
LocalDate startDate = new LocalDate(2014,1,2);
LocalDateTime startDateTime = new LocalDateTime(2014,1,2,00,0);
System.out.println(startDate.toDate());
System.out.println(startDateTime.toDate());
if(startDate.toDate().compareTo((startDateTime.toDate()))==0){
System.out.println("equal");
}
the output will be:
Thu Jan 02 00:00:00 IST 2014
Thu Jan 02 00:00:00 IST 2014
equal
If you want to check if say one date is in between another time frame, say is date1 4hrs in between date2, joda has different classes just for those scenarios you can use:
Hours h = Hours.hoursBetween(date1, date2);
Days s = Days.daysBetween(date1, date2);
Months m = Months.monthsBetween(date1,date2);
http://joda-time.sourceforge.net/apidocs/org/joda/time/base/BaseSingleFieldPeriod.html

Categories

Resources