Skip to content

Instantly share code, notes, and snippets.

@anis016
Created June 11, 2018 11:32
Show Gist options
  • Save anis016/7c1c3c4188490503f63a346bb095135c to your computer and use it in GitHub Desktop.
Save anis016/7c1c3c4188490503f63a346bb095135c to your computer and use it in GitHub Desktop.
1) getting earlier date from current date, 2) converting a yyyyMMdd to yyyMM format, 3) date comparision
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyyMM");
Calendar calendar = Calendar.getInstance();
// get the current date
// String currentDate = formatter.print(new DateTime(calendar.getTime()));
calendar.add(Calendar.YEAR, -year); // subtract n year from the current date
Date earlierDate = calendar.getTime(); // get the date
String baseLineDateString = formatter.print(new DateTime(earlierDate)); // format the date to yyyyMM formatted string
LocalDate baseLineDate = formatter.parseLocalDate(baseLineDateString); // convert the string to the LocalDate
////////////////////// this is for testing purpose /////////////////////////////////////
DateTimeFormatter testDashedFormatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
String testBaseLineDate = "2016-05-23";
DateTime testBaseLineDateTime = testDashedFormatter.parseDateTime(testBaseLineDate);
String testBaseLineDateString = formatter.print(testBaseLineDateTime);
LocalDate testLocalBaseLineDate = formatter.parseLocalDate(testBaseLineDateString);
System.out.println("test baseline date: " + testLocalBaseLineDate);
///////////////////////////////////////////////////////////////////////////////////////
DateTimeFormatter parserLongFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
String reportingDateLong = "2018-09-12";
DateTime dateTime = parserLongFormat.parseDateTime(reportingDateLong);
String reportingDateString = formatter.print(dateTime); // get the yyyyMM string formatted date
LocalDate reportingDate = formatter.parseLocalDate(reportingDateString); // convert the string to the LocalDate
System.out.println("reporting date: " + reportingDate);
// boolean isBefore = reportingDate.isBefore(baseLineDate);
boolean isBefore = reportingDate.isBefore(testLocalBaseLineDate);
// System.out.println(reportingDate + " is before " + baseLineDate + " : " + isBefore);
System.out.println(reportingDate + " is before " + testLocalBaseLineDate + " : " + isBefore);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment