Subtracting dates and get difference in days.How to subtract them? [duplicate] - java

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 8 years ago.
can anyone tell how to subtract string "after" from "today" to get days difference.
import java.text.*;
import java.util.*;
public class Main {
public static void main(String args[]){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
}
}

It would be easier with java8 where you dont need to subtract long values represent of date and change back to days, hours and minutes.
Date today= LocalDate.now();
Date futureDate = LocalDate.now().plusDays(1);
long days = Period.between(today, futureDate).getDays();
Period & LocalDate class are available in #java8
LocalDate docs
LocalDate is an immutable date-time object that represents a date,
often viewed as year-month-day. Other date fields, such as
day-of-year, day-of-week and week-of-year, can also be accessed. For
example, the value "2nd October 2007" can be stored in a LocalDate.
If you are not using java8, use joda-time library's org.joda.time.Days utility to calculate this
Days day = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Using JodaTime, in case you don't have Java 8
String timeValue = "2014/11/11";
DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("yyyy/MM/dd").toFormatter();
LocalDate startDate = LocalDate.parse(timeValue, parseFormat);
LocalDate endDate = startDate.plusDays(20);
System.out.println(startDate + "; " + endDate);
Period p = new Period(startDate, endDate);
System.out.println("Days = " + p.getDays());
System.out.println("Weeks = " + p.getWeeks());
System.out.println("Months = " + p.getMonths());
Which outputs...
2014-11-11; 2014-12-01
Days = 6
Weeks = 2
Months = 0

try this...
May it helps you.
import java.util.Date;
import java.util.GregorianCalendar;
// compute the difference between two dates.
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2010, 10, 10, 11, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}

This may help You..
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
Date d1 = null;
Date d2 = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
try {
d1 = format.parse(today);
d2 = format.parse(After);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Difference is "+diffDays+" Days");

Related

Converting difference between 2 dates to days in java 7 [duplicate]

This question already has answers here:
Calculating days between two dates with Java
(16 answers)
Closed 3 years ago.
I want to compare 2 dates in java and need to convert the difference between the 2 dates to days
//Setting up date
Calendar cal = Calendar.getInstance();
cal.set(2019, 5, 16);
Date d = cal.getTime();
Output would be something like this : Sun Jun 16 11:04:57 UTC 2019
//Getting the current date instance
Calendar cal1 = Calendar.getInstance();
Date d1 = cal1.getTime();
Output would be something like this : Mon Jul 08 11:04:57 UTC 2019
Need to get the difference between d & d1 in days.
Thanks in advance for taking your time to provide solution
Here, you just have to do simple math.
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormat.format(startDate)+" and "+
dateFormat.format(endDate)+" is "+
diffDays+" days.");
This will not work when crossing daylight savings time (or leap seconds) and might as well not give the expected results when using different times of day. You can modify it like this:
start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
diffDays++;
}
while (start.after(end)) {
start.add(Calendar.DAY_OF_MONTH, -1);
diffDays--;
}
Hope this helps. Good luck.
Simplest way:
public static long getDifferenceDays(Date d, Date d1) {
long diff = d1.getTime() - d.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

Checking dates if it is in a range

My Java FX app handles hours worked. I have work start and end time in 2 date fields. I succeeded in calculating the differences between 2 datesTime; but now how could I check if the result is in a night or day range???? The day begin at 6 and ends at 22h. For example someone who worked between 3Am till 11Pm.
Here is below how I did to have the total number of hours worked.
public void CalculNbreJourTravaille() {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyy HH:mm");
try {
Date ddtt = format.parse(ddt.getText());
Date dftt = format.parse(dft.getText());
long diff = dftt.getTime() - ddtt.getTime();
long diffhours = diff / (60*60*1000)%24;
long diffdays = diff/(24*60*60*1000);
long total = diffhours + (diffdays*24);
result.setText(total + " Hours");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
We have workers who can work beyond 10PM, and the pay would not be the same. If they work after 10pm, they will have a special pay. We pay at the end of the work. They could would work only 10 days or more.
You should use the new DateTimeFormatter class to give you a LocalDateTime object, which you can pull the hour from.
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime localDateTimeFrom = format.parse(dateFrom.getText(), LocalDateTime::from);
LocalDateTime localDateTimeTo = format.parse(dateTo.getText(), LocalDateTime::from);
int hoursFrom = localDateTimeFrom.getHour();
int hoursTo = localDateTimeTo.getHour();
boolean workedNight = hoursFrom < 6 || hoursTo > 22;
Here’s my attempt to cover all of your requirements. I wrote the code before reading that you don’t require that summer time (DST) is taken into account, so I am using ZonedDateTime to get correct hours also across summer time transitions. For the same reason I need to iterate over each day. For each date I calculate the hours worked at night time and the hours worked at day time.
If you want to make sure that summer time is not taken into account, use LocalDateTime instead of ZonedDateTime. In this case there may also be a possible performance gain in calculating the whole work days in one lump rather than one day at a time.
The code below uses 28/03/2018 03:00 and 29/03/2018 23:30 as example start and end time. Expected total hours worked are 44.5 since one day is 24 hours and there are 20.5 hours from 03:00 to 23:30. The expected day time hours are 32 since there are 16 daytime hours each of the two days. This leaves 12.5 hours as night time. And indeed the code prints
Day 32.0 hours; night 12.5 hours
The program follows. Please fill in the correct time zone where I put America/Monterey.
static ZoneId zone = ZoneId.of("America/Monterrey");
static LocalTime dayStart = LocalTime.of(6, 0);
static LocalTime dayEnd = LocalTime.of(22, 0);
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/uuuu H:mm");
public static void main(String[] args) {
String workStartString = "28/03/2018 03:00";
String workEndString = "29/03/2018 23:30";
calculateWorkingHours(workStartString, workEndString);
}
public static void calculateWorkingHours(String workStartString, String workEndString) {
ZonedDateTime workStart
= LocalDateTime.parse(workStartString, formatter).atZone(zone);
ZonedDateTime workEnd
= LocalDateTime.parse(workEndString, formatter).atZone(zone);
if (workEnd.isBefore(workStart)) {
throw new IllegalArgumentException("Work end must not be before work start");
}
LocalDate workStartDate = workStart.toLocalDate();
LocalDate workEndDate = workEnd.toLocalDate();
Duration workedDaytime = Duration.ZERO;
// first calculate work at nighttime before the start date, that is, work before 06:00
Duration workedNighttime
= calculateNightTime(workStartDate.minusDays(1), workStart, workEnd);
for (LocalDate d = workStartDate; ! d.isAfter(workEndDate); d = d.plusDays(1)) {
workedDaytime = workedDaytime.plus(calculateDayTime(d, workStart, workEnd));
workedNighttime = workedNighttime.plus(calculateNightTime(d, workStart, workEnd));
}
double dayHours = workedDaytime.toMinutes() / (double) TimeUnit.HOURS.toMinutes(1);
double nightHours = workedNighttime.toMinutes() / (double) TimeUnit.HOURS.toMinutes(1);
System.out.println("Day " + dayHours + " hours; night " + nightHours + " hours");
}
/**
* Calculates amount of work in daytime on d,
* that is between 06:00 and 22:00 on d.
* Only time that falls with in workStart to workAnd
* and also falls within 06:00 to 22:00 on d is included.
*
* #param d The date for which to calculate day work
* #param workStart
* #param workEnd
* #return Amount of daytime work on the said day
*/
private static Duration calculateDayTime(LocalDate d, ZonedDateTime workStart, ZonedDateTime workEnd) {
ZonedDateTime dayStartToday = d.atTime(dayStart).atZone(zone);
ZonedDateTime dayEndToday = d.atTime(dayEnd).atZone(zone);
if (workStart.isAfter(dayEndToday) || workEnd.isBefore(dayStartToday)) {
return Duration.ZERO;
}
// restrict calculation to daytime on d
if (workStart.isBefore(dayStartToday)) {
workStart = dayStartToday;
}
if (workEnd.isAfter(dayEndToday)) {
workEnd = dayEndToday;
}
return Duration.between(workStart, workEnd);
}
/**
* Calculates amount of night work in the night after d,
* that is from 22:00 on d until 06:00 the next morning.
*
* #param d The date for which to calculate night work
* #param workStart
* #param workEnd
* #return Amount of nighttime work in said night
*/
private static Duration calculateNightTime(LocalDate d, ZonedDateTime workStart, ZonedDateTime workEnd) {
assert ! workEnd.isBefore(workStart);
ZonedDateTime nightStart = d.atTime(dayEnd).atZone(zone);
ZonedDateTime nightEnd = d.plusDays(1).atTime(dayStart).atZone(zone);
if (workEnd.isBefore(nightStart) || workStart.isAfter(nightEnd)) {
return Duration.ZERO;
}
// restrict calculation to the night after d
if (workStart.isBefore(nightStart)) {
workStart = nightStart;
}
if (workEnd.isAfter(nightEnd)) {
workEnd = nightEnd;
}
return Duration.between(workStart, workEnd);
}
You can check the LocalTime part of a LocalDateTime to have a simple check using isAfter and isBefore.
I will use those values for this example.
LocalDateTime start = LocalDateTime.of(2018, Month.APRIL, 30, 23, 0);
LocalDateTime end = LocalDateTime.of(2018, Month.MAY, 1, 5, 0);
Then define the limit for the night.
LocalTime startNight = LocalTime.of(22, 0);
LocalTime endNight = LocalTime.of(6, 0);
And simply use get the LocalTime of both date and check if they are in the range. You can get the value using toLocalTime.
if(start.toLocalTime().isAfter(startNight) &&
end.toLocalTime().isBefore(endNight)){
System.out.println("NIGHT TIME");
} else {
System.out.println("DAY TIME");
}
NIGHT TIME
The output is valid since we start at 23:00 and end at 05:00.
Using this allow a simpler solution if you need to define a time like LocalTime.of(5,45) for 5:45
This is an example, this might need some adaptation if it is allowed to start part 22 but keep working after 6. This is just an example on how to use those methods.
This is easier, if you use the java.time API. You simply need to check, if the dates differ or if the starting time not in the range from 6:00 to 22:00:
private static final LocalTime START_TIME = LocalTime.of(6, 0); // 06:00
private static final LocalTime END_TIME = LocalTime.of(22, 0); // 22:00
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
// parse from input strings
LocalDateTime start = LocalDateTime.parse(startText, FORMATTER);
LocalDateTime end = LocalDateTime.parse(endText, FORMATTER);
boolean nightTime =
!start.toLocalDate().equals(end.toLocalDate())
|| start.toLocalTime().isBefore(START_TIME)
|| end.toLocalTime().isAfter(END_TIME);
// todo: change output to gui
System.out.println("night time: " + nightTime);
System.out.println("duration : " + Duration.between(start, end).toHours());
Define two formatters. One Fromatter to get date with time from edittext. And other On to get 12AM of that day. Now we need Date Objects corresponding to 6AM and 11PM of the same day. We can get those by adding that much milliseconds to the 12AM Object. These added dates can be used for comparison.
SimpleDateFormat df_zero_hours = new SimpleDateFormat("dd/MM/yyy");
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date ddtt = format.parse(ddt.getText()); //Work Start Time
Date dftt = format.parse(dft.getText()); //Work End Time
Date dateStart = df_zero_hours.parse(ddt.getText()); //12AM of the day job started
Date dayStart = new Date();
dayStart.setTime(dateStart.getTime()+6*60*60*1000); // Get 6AM of that day
Date dayEnd = new Date();
dayEnd.setTime(dateStart.getTime()+22*60*60*1000); //Get 10PM of that day
// Now check the worked hours. in Whatever way you need
boolean isBefore6AM = (dayStart.getTime()-ddtt.getTime())>0;
boolean isAfter10PM = (dftt.getTime()-dayEnd.getTime())>0;

write a program to prompt number of days to add to current date and print new date as well as today's date [duplicate]

This question already has answers here:
how to add days to java simple date format
(2 answers)
Closed 7 years ago.
print out today's date. this should be in the form MM/DD/YYYY. Months should start for 1 instead of 0. prompt to read number of days to be added to current date and print the new date.
please anyone help me out
import java.util.calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class JavaDateAdd {
public static void main(String[] args) {
Date date = new Date();
System.out.println("Today's Date Is: " + (now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DATE) + "/" + now.get(Calendar.YEAR));
System.out.print("Number of Days You Want To ADD: ");
int AddDays = in.nextInt();
Date newDate = addDays(date,AddDays);
System.out.println("Java Date after adding "+AddDays+" days: "+(now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DATE) + "/" + now.get(Calendar.YEAR));
}
}`
You can modify the code to accept take no of days and to accept your date format.
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// print current date
System.out.println("The current date is : " + cal.getTime());
// add 20 days to the calendar
cal.add(Calendar.DATE, 20);
System.out.println("20 days later: " + cal.getTime());
Date tommrrow = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String date = formatter.format(tommrrow);
System.out.println("20 days in dd-MM-yy: " + date);
}
Date Formatting using SimpleDateFormat:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example:
import java.util.*;
import java.text.*;
public class HelloWorld {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat sdf =
new SimpleDateFormat ("MM/dd/yyyy ");
System.out.println("Current Date: " + sdf.format(dNow));
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 35); // Adding 35 days
String output = sdf.format(c.getTime());
System.out.println("New Date: "+ output);
}
}
This would produce the following result:
Current Date: 09/24/2015
New Date: 10/29/2015
print out today's date. this should be in the form MM/DD/YYYY. Months should start for 1 instead of 0.
Start by taking a look at DateTimeFormatter, for example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
System.out.println("Today is " + formatter.format(LocalDateTime.now()));
prompt to read number of days to be added to current date
Start by having a look at Scanning, for example:
Scanner scanner = new Scanner(System.in);
System.out.print("How many days to add: ");
int days = scanner.nextInt();
and print the new date.
Start by having a look at Java 8's Date Time API, for example:
LocalDateTime ldt = LocalDateTime.now();
ldt = ldt.plusDays(days);
System.out.println(formatter.format(ldt));

Get date in past using java.util.Date

Below is code I am using to access the date in past, 10 days ago. The output is '20130103' which is today's date. How can I return todays date - 10 days ? I'm restricted to using the built in java date classes, so cannot use joda time.
package past.date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PastDate {
public static void main(String args[]){
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = new Date(System.currentTimeMillis());
Date oneDayBefore = new Date(myDate.getTime() - 10);
String dateStr = dateFormat.format(oneDayBefore);
System.out.println("result is "+dateStr);
}
}
you could manipulate a date with Calendar's methods.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = new Date(System.currentTimeMillis());
System.out.println("result is "+ dateFormat.format(myDate));
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DATE, -10);
System.out.println(dateFormat.format(cal.getTime()));
This line
Date oneDayBefore = new Date(myDate.getTime() - 10);
sets the date back 10 milliseconds, not 10 days. The easiest solution would be to just subtract the number of milliseconds in 10 days:
Date tenDaysBefore = new Date(myDate.getTime() - (10 * 24 * 60 * 60 * 1000));
Use Calendar.add(Calendar.DAY_OF_MONTH, -10).
The class Date represents a specific instant in time, with millisecond precision.
Date oneDayBefore = new Date(myDate.getTime() - 10);
So here you subtract only 10 milliseconds, but you need to subtract 10 days by multiplying it by 10 * 24 * 60 * 60 * 1000
You can also do it like this:
Date tenDaysBefore = DateUtils.addDays(new Date(), -10);
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
System.out.println(today30);

unable to get difference of days between two dates in java

I want to calculate the difference of days between two dates. My code works fine when the year of the date does not change, but when I calculate the difference between two dates like so: (13/01/2012 to 13/12/2011), it gives a negative value. It also gives wrong values of difference when I calculate the difference between today's date and a future date. Please help me. Thank you in advance. Here is my code:
//getting values from text box
String fromtext = from.getText().toString();
String totext = to.getText().toString();
//sdf if a simple date formatter
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date fromdate = (Date) sdf.parse(fromtext);
Date todate = (Date) sdf.parse(totext);
Calendar fromcal = Calendar.getInstance();
Calendar tocal = Calendar.getInstance();
fromcal.setTime(fromdate);
tocal.setTime(todate);// setting to date
int reportDays=(int)(todate.getTime()-fromdate.getTime())/(3600*24*1000);
please tell me what is the best way to calculate the difference in days.
Dates input : 13/01/2012, 13/12/2011
format seems dd/MM/yyyy and you are using wrong one (i.e. MM/dd/yyyy)
tl;dr
ChronoUnit.DAYS.between(
LocalDate.parse( "13/01/2012" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ,
LocalDate.parse( "13/12/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
)
Using java.time
Much easier with the modern java.time classes that supplant the troublesome old legacy date-time classes such as Date & Calendar.
(13/01/2012 to 13/12/2011),
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate start = LocalDate.parse( "13/01/2012" , f );
LocalDate stop = LocalDate.parse( "13/12/2011" , f );
Use ChronoUnit to calculate elapsed days.
long days = ChronoUnit.DAYS.between( start , stop );
Of course the number of days is negative when going back in time. Notice how your stop date is earlier than your start date.
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 abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
You can use ChronoUnit again to count days into the future.
long days = ChronoUnit.DAYS.between( today , today.plusMonths( 7 ) );
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?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
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.
In addition to the format issue already mentionned, you are likely to have an overflow.
Try this:
int reportDays=(int)((todate.getTime()-fromdate.getTime())/(3600*24*1000));
I think you should try better googling....
http://www.java2s.com/Code/Java/Development-Class/DateDiffcomputethedifferencebetweentwodates.htm
Using joda time would be the simplest way.
check this code:
import java.util.Calendar;
public class DateDifferent{
public static void main(String[] args){
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2007, 01, 10);
calendar2.set(2007, 07, 01);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff + " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
System.out.println("Time in days: " + diffDays + " days.");
}
}
Here's a simple little class I wrote for this purpose:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DifferenceInDays
{
public int dateOffset(String incomingDate) throws ParseException
{
// parse dates
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) formatter.parse(incomingDate);
// convert to milliseconds
long millisecs = date.getTime();
// convert to days
int offsetInDays = (int) Math.abs(millisecs / (1000 * 60 * 60 * 24));
return offsetInDays;
}
}
It takes care of negative offsets using the absolute value method.
If you try this with a locale that has daylight saving, and the from and to dates are before and after a daylight saving change the result may be different by 1 day. This is because Date and Calendar use timezones.
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:
public static int daysSince1900(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
int year = c.get(Calendar.YEAR);
if (year < 1900 || year > 2099) {
throw new IllegalArgumentException("daysSince1900 - Date must be between 1900 and 2099");
}
year -= 1900;
int month = c.get(Calendar.MONTH) + 1;
int days = c.get(Calendar.DAY_OF_MONTH);
if (month < 3) {
month += 12;
year--;
}
int yearDays = (int) (year * 365.25);
int monthDays = (int) ((month + 1) * 30.61);
return (yearDays + monthDays + days - 63);
}
Thus, to get the difference in days between two dates, you calculate their days since 1900 and calc the difference. Our daysBetween method looks like this:
public static Integer getDaysBetween(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return null;
}
int days1 = daysSince1900(date1);
int days2 = daysSince1900(date2);
if (days1 < days2) {
return days2 - days1;
} else {
return days1 - days2;
}
}
And don't ask me where this calculation came from because we've used it since the early '90s.
I would do it like this!
package javaapplication2;
//#author Ibrahim Yesilay
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) throws ParseException {
Scanner scan = new Scanner(System.in);
System.out.println("First dates Day :");
int d = scan.nextInt();
System.out.println("First dates Mounth :");
int m = scan.nextInt();
System.out.println("First dates Year :");
int y = scan.nextInt();
String date;
date = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date firstdate = null;
firstdate = dateFormat.parse(date);
System.out.println(dateFormat.format(firstdate));
System.out.println("Second dates Day :");
d = scan.nextInt();
System.out.println("Second dates Month :");
m = scan.nextInt();
System.out.println("Second dates Year :");
y = scan.nextInt();
date = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);
Date seconddate = null;
seconddate = dateFormat.parse(date);
System.out.println(dateFormat.format(seconddate));
if (seconddate.getTime() > firstdate.getTime()) {
long sonuc = (long)(seconddate.getTime()- firstdate.getTime())/(3600*24*1000);
System.out.println("" + sonuc);
} else if (firstdate.getTime() > seconddate.getTime()) {
long sonuc = (long)(firstdate.getTime()- seconddate.getTime())/(3600*24*1000);
System.out.println("" + sonuc);
} else {
System.out.println("The dates are equal!");
}
}
}

Categories