I'm trying to break a range of dates into equal intervals. Here is the code that I'm using. (Dates are in YYYY-MM-dd format)
Integer frequency= 4;
Date startDate = '2020-02-27';
Date endDate = '2022-02-26';
String[] startD = string.valueOf(behadelPlan.Start_datum__c).split('-');
String[] endD = string.valueOf(behadelPlan.Einddatum__c).split('-');
//String[] dates;
Integer x = 0;
Integer startYear = Integer.valueof(startD[0]);
Integer endYear = Integer.valueof(endD[0]);
//while (x < 4) {
for (Integer i = startYear; i <= endYear; i++) {
Integer endMonth = i != endYear ? 11 : Integer.valueof(endD[1]) - 1;
Integer startMon = i == startYear ? Integer.valueof(startD[1]) - 1 : 0;
for (Integer j = startMon; j <= endMonth && x < frequency; j = j + 1) {
Integer month = j + 1;
String displayMonth;
if (month < 10) {
displayMonth = '0' + month;
} else {
displayMonth = String.valueOf(month);
}
List<string> slist = new string[]{string.valueOf(i), displayMonth, '01'};
string allstring = string.join(sList,'-');
System.debug(slist);
x+=1;
}
}
when I run this I get the output as
2020-02-01
2020-03-01
2020-04-01
2020-05-01
Here In my case, I want to generate the dates at equal(monthly with the day being start dates day) intervals. In the above example, I should be getting the resultant dates as 4 equal intervals (as I've given my frequency in a number of months).
Please let me know on how can I achieve this.
Here is a simple example.
startdate = '2020-01-01'
endDate = '2020-12-01'
frequency = 4
output should be
2020-01-01
2020-03-01
2020-06-01
2020-09-01
Here is how I would do it. I will us class Calendar for this.
public class FrequencyTransform {
public static void main (String[] args) {
System.out.println("Split a date into equal intervals based on a given frequency");
Integer frequency= 4;
try {
Date startDate = new SimpleDateFormat("yyyy-mm-dd").parse("2020-02-27");
Date endDate = new SimpleDateFormat("yyyy-mm-dd").parse("2021-02-26");
Calendar startCalendar = Calendar.getInstance();
startCalendar.clear();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.clear();
endCalendar.setTime(endDate);
// id you want the interval to be months
int monthsElapsed = elapsed(startCalendar, endCalendar, Calendar.MONTH);
System.out.println("Number of months between dates:" + monthsElapsed);
int interval = monthsElapsed % frequency;
System.out.println("For the frequency 4 the interval is: " + interval);
while (!startCalendar.after(endCalendar)){
startCalendar.add(Calendar.MONTH,interval);
Date auxDate= startCalendar.getTime();
System.out.println(auxDate);
}
}
catch (ParseException ex) {
ex.printStackTrace();
}
}
private static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected.
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
}
This is just a quick example. You can take it from here. The thing is Calendar allow you to use different time units. Instead of Calendar.MONTH you can use Calendar.DATE for days, Calendar.YEAR for year. Wasn't very sure how you wanted to do the split.
Sample code ,
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SOTest {
static DateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd");
public static void main(String[] args) {
try {
String startDateString = "2020-01-01";
String endDateString = "2020-12-01";
int frequency = 4;
Date startDate = (Date)dateFormat.parse(startDateString);
Date endDate = (Date)dateFormat.parse(endDateString);
Long intervalSize = (endDate.getTime()-startDate.getTime())/frequency;
for(int i=0; i<= frequency && intervalSize > 0; i++) {
Date date = new Date(startDate.getTime()+intervalSize*i);
System.out.println("Date :: "+dateFormat.format(date));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
output for above ::
Date :: 2020-01-01
Date :: 2020-03-24
Date :: 2020-06-16
Date :: 2020-09-08
Date :: 2020-12-01
For input :: startDate = '2020-02-27' , endDate = '2022-02-26', interval = 4
Date :: 2020-02-27
Date :: 2020-08-27
Date :: 2021-02-26
Date :: 2021-08-27
Date :: 2022-02-26
I'm trying to generate a random date of birth for people in my database using a Java program. How would I do this?
import java.util.GregorianCalendar;
public class RandomDateOfBirth {
public static void main(String[] args) {
GregorianCalendar gc = new GregorianCalendar();
int year = randBetween(1900, 2010);
gc.set(gc.YEAR, year);
int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR));
gc.set(gc.DAY_OF_YEAR, dayOfYear);
System.out.println(gc.get(gc.YEAR) + "-" + (gc.get(gc.MONTH) + 1) + "-" + gc.get(gc.DAY_OF_MONTH));
}
public static int randBetween(int start, int end) {
return start + (int)Math.round(Math.random() * (end - start));
}
}
java.util.Date has a constructor that accepts milliseconds since The Epoch, and java.util.Random has a method that can give you a random number of milliseconds. You'll want to set a range for the random value depending on the range of DOBs that you want, but those should do it.
Very roughly:
Random rnd;
Date dt;
long ms;
// Get a new random instance, seeded from the clock
rnd = new Random();
// Get an Epoch value roughly between 1940 and 2010
// -946771200000L = January 1, 1940
// Add up to 70 years to it (using modulus on the next long)
ms = -946771200000L + (Math.abs(rnd.nextLong()) % (70L * 365 * 24 * 60 * 60 * 1000));
// Construct a date
dt = new Date(ms);
Snippet for a Java 8 based solution:
Random random = new Random();
int minDay = (int) LocalDate.of(1900, 1, 1).toEpochDay();
int maxDay = (int) LocalDate.of(2015, 1, 1).toEpochDay();
long randomDay = minDay + random.nextInt(maxDay - minDay);
LocalDate randomBirthDate = LocalDate.ofEpochDay(randomDay);
System.out.println(randomBirthDate);
Note: This generates a random date between 1Jan1900 (inclusive) and 1Jan2015 (exclusive).
Note: It is based on epoch days, i.e. days relative to 1Jan1970 (EPOCH) - positive meaning after EPOCH, negative meaning before EPOCH
You can also create a small utility class:
public class RandomDate {
private final LocalDate minDate;
private final LocalDate maxDate;
private final Random random;
public RandomDate(LocalDate minDate, LocalDate maxDate) {
this.minDate = minDate;
this.maxDate = maxDate;
this.random = new Random();
}
public LocalDate nextDate() {
int minDay = (int) minDate.toEpochDay();
int maxDay = (int) maxDate.toEpochDay();
long randomDay = minDay + random.nextInt(maxDay - minDay);
return LocalDate.ofEpochDay(randomDay);
}
#Override
public String toString() {
return "RandomDate{" +
"maxDate=" + maxDate +
", minDate=" + minDate +
'}';
}
}
and use it like this:
RandomDate rd = new RandomDate(LocalDate.of(1900, 1, 1), LocalDate.of(2010, 1, 1));
System.out.println(rd.nextDate());
System.out.println(rd.nextDate()); // birthdays ad infinitum
You need to define a random date, right?
A simple way of doing that is to generate a new Date object, using a long (time in milliseconds since 1st January, 1970) and substract a random long:
new Date(Math.abs(System.currentTimeMillis() - RandomUtils.nextLong()));
(RandomUtils is taken from Apache Commons Lang).
Of course, this is far to be a real random date (for example you will not get date before 1970), but I think it will be enough for your needs.
Otherwise, you can create your own date by using Calendar class:
int year = // generate a year between 1900 and 2010;
int dayOfYear = // generate a number between 1 and 365 (or 366 if you need to handle leap year);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, randomYear);
calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
Date randomDoB = calendar.getTime();
For Java8 -> Assumming the data of birth must be before current day:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Random;
public class RandomDate {
public static LocalDate randomBirthday() {
return LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
}
public static void main(String[] args) {
System.out.println("randomDate: " + randomBirthday());
}
}
If you don't mind adding a new library to your code you can use MockNeat (disclaimer: I am one of the authors).
MockNeat mock = MockNeat.threadLocal();
// Generates a random date between [1970-1-1, NOW)
LocalDate localDate = mock.localDates().val();
System.out.println(localDate);
// Generates a random date in the past
// but beore 1987-1-30
LocalDate min = LocalDate.of(1987, 1, 30);
LocalDate past = mock.localDates().past(min).val();
System.out.println(past);
LocalDate max = LocalDate.of(2020, 1, 1);
LocalDate future = mock.localDates().future(max).val();
System.out.println(future);
// Generates a random date between 1989-1-1 and 1993-1-1
LocalDate start = LocalDate.of(1989, 1, 1);
LocalDate stop = LocalDate.of(1993, 1, 1);
LocalDate between = mock.localDates().between(start, stop).val();
System.out.println(between);
Generating random Date of Births:
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(randomDOB());
}
}
public static String randomDOB() {
int yyyy = random(1900, 2013);
int mm = random(1, 12);
int dd = 0; // will set it later depending on year and month
switch(mm) {
case 2:
if (isLeapYear(yyyy)) {
dd = random(1, 29);
} else {
dd = random(1, 28);
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dd = random(1, 31);
break;
default:
dd = random(1, 30);
break;
}
String year = Integer.toString(yyyy);
String month = Integer.toString(mm);
String day = Integer.toString(dd);
if (mm < 10) {
month = "0" + mm;
}
if (dd < 10) {
day = "0" + dd;
}
return day + '/' + month + '/' + year;
}
public static int random(int lowerBound, int upperBound) {
return (lowerBound + (int) Math.round(Math.random()
* (upperBound - lowerBound)));
}
public static boolean isLeapYear(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
int noOfDays = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
if (noOfDays > 365) {
return true;
}
return false;
}
}
You can checkout randomizer for random data generation.This library helps to create random data from given Model class.Checkout below example code.
public class Person {
#DateValue( from = "01 Jan 1990",to = "31 Dec 2002" , customFormat = "dd MMM yyyy")
String dateOfBirth;
}
//Generate random 100 Person(Model Class) object
Generator<Person> generator = new Generator<>(Person.class);
List<Person> persons = generator.generate(100);
As there are many built in data generator is accessible using annotation,You also can build custom data generator.I suggest you to go through documentation provided on library page.
Look this method:
public static Date dateRandom(int initialYear, int lastYear) {
if (initialYear > lastYear) {
int year = lastYear;
lastYear = initialYear;
initialYear = year;
}
Calendar cInitialYear = Calendar.getInstance();
cInitialYear.set(Calendar.YEAR, 2015);
long offset = cInitialYear.getTimeInMillis();
Calendar cLastYear = Calendar.getInstance();
cLastYear.set(Calendar.YEAR, 2016);
long end = cLastYear.getTimeInMillis();
long diff = end - offset + 1;
Timestamp timestamp = new Timestamp(offset + (long) (Math.random() * diff));
return new Date(timestamp.getTime());
}
I think this will do the trick:
public static void main(String[] args) {
Date now = new Date();
long sixMonthsAgo = (now.getTime() - 15552000000l);
long today = now.getTime();
for(int i=0; i<10; i++) {
long ms = ThreadLocalRandom.current().nextLong(sixMonthsAgo, today);
Date date = new Date(ms);
System.out.println(date.toString());
}
}
If you don't mind a 3rd party library, the Utils library has a RandomDateUtils that generates random java.util.Dates and all the dates, times, instants, and durations from Java 8's date and time API
LocalDate birthDate = RandomDateUtils.randomPastLocalDate();
LocalDate today = LocalDate.now();
LocalDate under18YearsOld = RandomDateUtils.randomLocalDate(today.minus(18, YEARS), today);
LocalDate over18YearsOld = RandomDateUtils.randomLocalDateBefore(today.minus(18, YEARS));
It is in the Maven Central Repository at:
<dependency>
<groupId>com.github.rkumsher</groupId>
<artifactId>utils</artifactId>
<version>1.3</version>
</dependency>
simplest method:
public static LocalDate randomDateOfBirth() {
final int maxAge = 100 * 12 * 31;
return LocalDate.now().minusDays(new Random().nextInt(maxAge));
}
Using the original answer and adapting it to the new java.time.* api and adding ways to generate n random dates -- the function will return a List.
// RandomBirthday.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class RandomBirthday {
public static List<String> getRandomBirthday(int groupSize, int minYear, int maxYear) {
/** Given a group size, this method will return `n` random birthday
* between 1922-2022 where `n=groupSize`.
*
* #param groupSize the number of random birthday to return
* #param minYear the min year [lower bound]
* #param maxYear the max year [upper bound]
* #return a list of random birthday with format YYYY-MM-DD
*/
ArrayList<String> birthdays = new ArrayList<>();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (int i = 0; i < groupSize; i++) {
LocalDate baseDate = LocalDate.now();
LocalDate baseYear = baseDate.withYear(ThreadLocalRandom.current().nextInt(minYear, maxYear));
int dayOfYear = ThreadLocalRandom.current().nextInt(1, baseYear.lengthOfYear());
LocalDate baseRandBirthday = baseYear.withDayOfYear(dayOfYear);
LocalDate randDate = LocalDate.of(
baseRandBirthday.getYear(),
baseRandBirthday.getMonth(),
baseRandBirthday.getDayOfMonth()
);
String formattedDate = dateFormat.format(randDate);
birthdays.add(formattedDate);
}
return birthdays;
}
public static void main(String[] args) {
// main method
List<String> bDay = getRandomBirthday(40, 1960, 2022);
System.out.println(bDay);
}
}
I am studying Scala and ended up Googling Java solutions for choosing a random date between range. I found this post super helpful and this is my final solution. Hope it can help future Scala and Java programmers.
import java.sql.Timestamp
def date_rand(ts_start_str:String = "2012-01-01 00:00:00", ts_end_str:String = "2015-01-01 00:00:00"): String = {
val ts_start = Timestamp.valueOf(ts_start_str).getTime()
val ts_end = Timestamp.valueOf(ts_end_str).getTime()
val diff = ts_end - ts_start
println(diff)
val ts_rand = new Timestamp(ts_start + (Random.nextFloat() * diff).toLong)
return ts_rand.toString
} //> date_rand: (ts_start_str: String, ts_end_str: String)String
println(date_rand()) //> 94694400000
//| 2012-10-28 18:21:13.216
println(date_rand("2001-01-01 00:00:00", "2001-01-01 00:00:00"))
//> 0
//| 2001-01-01 00:00:00.0
println(date_rand("2001-01-01 00:00:00", "2010-01-01 00:00:00"))
//> 283996800000
//| 2008-02-16 23:15:48.864 //> 2013-12-21 08:32:16.384
int num = 0;
char[] a={'a','b','c','d','e','f'};
String error = null;
try {
num = Integer.parseInt(request.getParameter("num"));
Random r = new Random();
long currentDate = new Date().getTime();
ArrayList<Student> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
String name = "";
for (int j = 0; j < 6; j++) {
name += a[r.nextInt(5)];
}
list.add(new Student(i + 1, name, r.nextBoolean(), new Date(Math.abs(r.nextLong() % currentDate))));
}
request.setAttribute("list", list);
request.setAttribute("num", num);
request.getRequestDispatcher("student.jsp").forward(request, response);
} catch (NumberFormatException e) {
error = "Please enter interger number";
request.setAttribute("error", error);
request.getRequestDispatcher("student.jsp").forward(request, response);
}
I am working on a small exercise to test myself. I made a small program to print the date/days in the current month. I assumed that you would be given the current date e.g. May 10th and the current day Thursday. My question, is it possible to do this exercise without being given the date today and the day? Here's my code:
public static void main(String [] args) {
int days = 31; // may
String arr[] = new String[]{"Mon", "Tue", "Wed", "Thur", "Fri","Sat", "Sun"};
int today_date = 10;
String today_day = "Thur";
int today_index = 0;
//get index of current day e.g. Thur = index 3
for(int i = 0; i<arr.length; i++) {
if(today_day.equals(arr[i])) {
today_index = i;
}
}
//count from today_day to 1, the purpose is to get the first day of the month
while(today_date > 1) {
if(today_index == 0) {
today_index = 6;
today_date--;
}
else {
today_date--;
today_index--;
}
}
//print each day of the month
for(int i = 1; i<=days; i++ ) {
if(today_index == 6) {
System.out.print(i+"("+ arr[today_index]+") \n");
today_index = 0;
}
else {
System.out.print(i+"("+ arr[today_index]+") | ");
today_index++;
}
}
}
Sample output:
Create key value pair for mapping "integer to name of month" and "integer to day in a week". (Switch case can also be used)
Use Calendar which is part of java.util package and get day of the week for given date, month and year.
Ex:
Calendar cal = new GregorianCalendar();
cal.set(Calendar.MONTH, 4);
cal.set(Calendar.DAY_OF_MONTH, 15);
cal.set(Calendar.YEAR, 2018);
System.out.println(cal.getTime());
System.out.println(cal.getDisplayName(2, 3, Locale.US));
Use "integer to day in a week" key value pair to print respective day and month in words.
Hope this helps.
This question already has answers here:
Calculate number of weekdays between two dates in Java
(20 answers)
Closed 6 years ago.
StartDate: 2016-05-8 20:16:00;
EndDate: 2016-05-30 20:16:00;
public int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (c1.after(c2)) {
if (c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
sundays++;
saturday++;
c2.add(Calendar.DATE, 1);
c2.add(Calendar.DATE, 1);
}
System.out.println(sundays);
return saturday + sundays;
}
In this function I am trying to get total count of Saturdays and Sundays between two dates. But when I pass the date I get zero as a result. Please point out the mistake and suggest corrections.
It is not advisable to write full program but since you put effort, here is what seems to be working on my system and returning a value of 7.
public class CountWeekends {
public static void main(String[] args){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
int count = 0;
try {
Date d1 = formatter.parse("2016-05-8 20:16:00");
Date d2 = formatter.parse("2016-05-30 20:16:00");
count = saturdaysundaycount(d1,d2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count of Sats & Sundays = "+count);
}
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (! c1.after(c2)) {
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
saturday++;
}
if(c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
sundays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Saturday Count = "+saturday);
System.out.println("Sunday Count = "+sundays);
return saturday + sundays;
}
Logic: You need to keep increment start date by one day till it
surpasses end date and keep checking day on start date.
The problem is in your while, with this piece of code is working fine for me.
Check the endDate and startDate because I guess that you are sending it in the wrong order.
while (endDate.after(startDate)) {
if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ){
sundays++;
}else if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
saturday++;
}
endDate.add(Calendar.DATE, -1);
}
Your code does not loop through the days. Please try the following code. In the while loop it loops through all the days between the given fist date and last date. It does this by adding a day to c1 in every iteration until c1 is after c2. This gives number of Saturdays and Sundays between given dates including those two days.
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturdays = 0;
while (!c1.after(c2)) {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-E");
String formatted = format1.format(c1.getTime());
System.out.println("Current Date C1 : " + formatted);
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
sundays++;
} else if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
saturdays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Sundays : " + sundays);
System.out.println("Saturdays : " + saturdays);
return saturdays + sundays;
}
public static int getNumberofSundays(String d1,String d2) throws Exception{ //object in Date form
Date date1=getDate(d1);
Date date2=getDate(d2);
Calendar c1=Calendar.getInstance();
c1.setTime(date1);
Calendar c2=Calendar.getInstance();
c2.setTime(date2);
int sundays=0;
while(c1.after(c2)){
if(c2.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
sundays++;
c2.add(Calendar.DATE,1);
}
}
System.out.println("number of days between 2 dates"+sundays);
return sundays;
}
I need to get the full days between two dates in java (the dates are given in Date type) .
For example:
01/01/2015/12:00:00 - 01/02/2015/11:59:00 isn't a full day
and i need to consider daylight savings.
I know that jodatime lib does that but i reached the 65k method limit and i cant use jodatime lib.
i tried the millisecond diff way and the while loop that uses the "before" method:
Android/Java - Date Difference in days
I manage to figure it out:
i used some of this code - https://stackoverflow.com/a/28865648/3873513
and added some of mine:
public static int calcDaysDiff(Date day1, Date day2) {
Date d1 = new Date(day1.getTime());
Date d2 = new Date(day2.getTime());
Calendar date1 = Calendar.getInstance();
date1.setTime(d1);
Calendar date2 = Calendar.getInstance();
date2.setTime(d2);
//checks if the start date is later then the end date - gives 0 if it is
if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
}
//checks if there is a daylight saving change between the two dates
int offset = calcOffset(d1, d2);
if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
//swap them
Calendar temp = date1;
date1 = date2;
date2 = temp;
}
return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}
// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
return 0;
}
return -1;
}
// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
int extraDays = 0;
while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
dayTwo.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
}
}
public class DateDiff {
public static void main(String[] av) {
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
String inputString1 = "01/01/2015/12:00:00";
String inputString2 = "01/02/2015/11:59:00";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime(); // Calculate the different
int days = (int) (diff / (1000*60*60*24)); // This convert milliseconds to days
System.out.println ("Days differ: " + days);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following code will calculate the two dates given, the result print is:
Days differ: 0