-5

This program tells me which time a start date and an end, now I ask you whether you want to enter another period when you s (yes) adds the starting period, but this want to join with above, for example, I add the following:

16/08/1993 - 09/09/2014 = 21 years, 0 months, 24 days.

14/02/1995 - 18/05/2001 = 6 years, 3 months, 35 days

Total:.................................27 years, 3 months y 59 days

NOTE: I do not know if something is wrong and try everything. I am new to java.

public void diferencia(){
char seguir=0;
Scanner teclado =new Scanner(System.in);
do{
System.out.println("day/Month/year ");
System.out.println("Write the first date: ");
String dayini = teclado.next();
System.out.println("write the second date: ");
String dateactual = teclado.next();

String[] aFechaIng = dateini.split("/");
Integer dayini = Integer.parseInt(aFechaIng[0]);
Integer monthini = Integer.parseInt(aFechaIng[1]);
Integer yearini = Integer.parseInt(aFechaIng[2]);

String[] aFecha = dateactual.split("/");
Integer dayactual= Integer.parseInt(aFecha[0]);
Integer monthactual = Integer.parseInt(aFecha[1]);
Integer yearactual = Integer.parseInt(aFecha[2]);


int b = 0;
int days = 0; //DAYS
int month = 0;  //MONTH
int years = 0;  //YEARS
int months = 0;  //MONTHS
month = monthini - 1;
// LEAP YEAR
if(month==2){
if ((yearactual % 4 == 0) && ((yearactual % 100 != 0) || (yearactual % 400 == 0))){
b = 29;
}else{
b = 28;
}
}else if(month <= 7){
if(month == 0){
b = 31;
}else if(month % 2==0){
b = 30;
}else{
b = 31;
}
}else if(month > 7){
if(month % 2 == 0){
b = 31;
}else{
b = 30;
}
}
if((yearini > yearactual) || (yearini == yearactual && monthini > monthactual) ||
(yearini == yearactual && monthini == monthactual && dayini > dayactual)){
// errors
System.out.println("The start date must be minor ");
}else{ //time periods
if(monthini <= monthactual){
years = yearactual - yearini;
if (dayini <= dayactual){
mmonths = monthactual - monthini;
days = b - (dayini - dayactual);
}else{
if(monthactual == monthini){
years = years - 1;
}
months = (monthactual - monthini - 1 + 12) % 12;
days = b - (dayini - dayactual);
}
}else{
years = yearactual - yearini - 1;
//System.out.println("Años?¿: " + anios);
if(dayini > dayactual){
months = monthactual - monthsini - 1 + 12;
days = b - (dayini - dayactual);
}else{
months = monthactual - monthini + 12;
days = dayactual - dayini;
}
}
}

System.out.println("Years: "+years);
System.out.println("Months: "+months);
System.out.println("Days: "+days);
System.out.println("You want to add another period?? ");
seguir = teclado.next().charAt(0);
}while(seguir!='n');
}//finish method diferencia
danielbmz
  • 31
  • 1
  • 1
  • 8
  • 3
    format your code and put variables in English. it's pretty unreadable as is – Ajk_P Sep 09 '14 at 15:59
  • You already asked [this question](http://stackoverflow.com/q/25731178/642706) less than 24 hours ago. – Basil Bourque Sep 09 '14 at 16:03
  • @DANIELBMZ Your math in incorrect. `14/02/1995 - 18/05/2001 = 6 years, 3 months, 35 days` should be `14/02/1995 - 18/05/2001 = 6 years, 3 months, 4 days`. Four days, not thirty-five. – Basil Bourque Sep 10 '14 at 01:05

3 Answers3

2

Use joda-time...

    Scanner in = new Scanner(System.in);
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String input;
    long totalDuration=0;

    while (!(input = in.nextLine()).equals("quit")) {
        // todo validate input
        String[] dates = input.split("-");
        Date start = sdf.parse(dates[0].trim());
        Date end = sdf.parse(dates[1].trim());

        long duration = end.getTime() - start.getTime();
        Period period = new Period(0, duration, PeriodType.yearMonthDay());

        System.out.println("Duration: " + period.getYears() + "years " + period.getMonths() + "months " + period.getDays() + "days");

        totalDuration += duration;
    }

    Period total = new Period(0, totalDuration, PeriodType.yearMonthDay());
    System.out.println("Total duration is: " + total.getYears() + "years " + total.getMonths() + "months " + total.getDays() + "days");

Btw, variables named in English and formatted code is easier to read ;)

Olli Puljula
  • 2,471
  • 1
  • 14
  • 8
0

Before begining your loop create three variables wich are totalAnios (totalYears), totalMeses (totalMonths) , totalDias (totalDays) and initialize them to 0.

   int totalAnios = 0;
   int totalMeses = 0;
   int totalDias = 0; 
   do {
     ....
   }

And before closing the loop (before while(...) ) you have to add the difference of years, months and days to the previous varibales you created ( totalAnios , totalMeses , totalDias ) and print the result.

do {
 ... 
 /* your calculation goes here */

   totalAnios += anios;
   totalMeses += meses;
   totalDias  += dias;

            System.out.println("total : " + totalAnios + " " + totalMeses + " " + totalDias);
} while (seguir != 'n');

Each time the user choose to stay in the loop, we sum the previous results and print the total.

By the way, next time don't forget to format your code and put variables in english ;) .

akSahli
  • 16
  • 3
  • in the result, the months show full. for example: 5 years, 36 months and 52 days. how to this days and months, transform months in years or days in months. for example: 5 years, 36 months and 52 days to 8 years 1 months and 21 days – danielbmz Sep 09 '14 at 17:54
  • @DANIELBMZ, if you assume that each month have 30 days, then months = days/30 and the remaining days = days%30.(same thing for months and years). But you should use Joda-time, wich provide a better way to do this. http://www.joda.org/joda-time/ – akSahli Sep 10 '14 at 07:43
0

Sample Data Is Incorrect

Your math is incorrect. 14/02/1995 - 18/05/2001 = 6 years, 3 months, 35 days should be 14/02/1995 - 18/05/2001 = 6 years, 3 months, 4 days. Four days, not thirty-five.

Joda-Time

The Joda-Time library has this functionality built-in. No need to re-invent the wheel.

The java.time package in Java 8 may have something similar. This package was inspired by Joda-Time but is re-architected.

Avoid the java.util.Date and .Calendar classes bundled with Java. They are notoriously troublesome. Oracle/Sun decided to supplant them with the new java.time package.

ISO 8601

The strings you see here are defined by the ISO 8601 standard, the default for both Joda-Time and java.time when generating/parsing strings.

A date-time is YYYY-MM-DDTHH:MM:SS.SSS±HH:MM. Alternatively, a Z for an offset of zero, meaning Zulu time, meaning UTC.

In the standard, a Duration (what Joda-Time calls Period) is written as: PnYnMnDTnHnMnS. The T separates the date portion from time portion. The P starts every value.

Normalizing Period

In comment, the original poster asked for a combination of periods to be normalized. That is, adjust the numbers so rather than "7 weeks" we get "1 month, 3 weeks". The example shows how to do that. Just beware such normalizing assumes a 12 month year, 7 day week, 24 hour day, 60 minute hour and 60 second minute. This assumption may or may not fit your business rules.

Period Type

Play around with passing a PeriodType object if you want to specify a different kind of Period. Perhaps you want months and days without any weeks.

Duration

Joda-Time also offers a Duration class that tracks exact milliseconds between a pair of date-time values. This serves as an alternative to Period where we track time as chunks of years, months, and such rather than precise elapsed time.

Time Zone

You may or may not want to be using a time zone. If not, use DateTimeZone.UTC for 24-hour days.

Example code in Joda-Time 2.4

DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // or DateTimeZone.UTC

DateTime start_a = new DateTime( "1993-08-16" , timeZone ); // Could call `.withTimeAtStartOfDay()` but that is the default behavior for date-only string.
DateTime stop_a = new DateTime( "2014-09-09" , timeZone );
Interval interval_a = new Interval( start_a , stop_a );
Period period_a = interval_a.toPeriod();

DateTime start_b = new DateTime( "1995-02-14" , timeZone );
DateTime stop_b = new DateTime( "2001-05-18" , timeZone );
Interval interval_b = new Interval( start_b , stop_b );
Period period_b = interval_b.toPeriod();

Period periodCombined = period_a.plus( period_b );
Period periodCombinedNormalized = periodCombined.normalizedStandard(); // Assumes that all years are 12 months, all weeks are 7 days, all days are 24 hours, all hours are 60 minutes and all minutes are 60 seconds. Not true for Daylight Saving Time and other anomalies.

Dump to console.

System.out.println( "start_a:" + start_a );
System.out.println( "stop_b:" + stop_b );
System.out.println( "interval_a:" + interval_a );
System.out.println( "period_a:" + period_a );

System.out.println( "start_b:" + start_b );
System.out.println( "stop_b:" + stop_b );
System.out.println( "interval_b:" + interval_b );
System.out.println( "period_b:" + period_b );

System.out.println( "periodCombined:" + periodCombined );
System.out.println( "periodCombinedNormalized:" + periodCombinedNormalized );

When run.

start_a:1993-08-16T00:00:00.000-04:00
stop_b:2001-05-18T00:00:00.000-04:00
interval_a:1993-08-16T00:00:00.000-04:00/2014-09-09T00:00:00.000-04:00
period_a:P21Y3W3D
start_b:1995-02-14T00:00:00.000-05:00
stop_b:2001-05-18T00:00:00.000-04:00
interval_b:1995-02-14T00:00:00.000-05:00/2001-05-18T00:00:00.000-04:00
period_b:P6Y3M4D
periodCombined:P27Y3M3W7D
periodCombinedNormalized:P27Y3M4W

Date-Only

If you want to work with date-only, and no time-of-day nor time zone, then you can use the LocalDate class offered by both Joda-Time and java.time. The handy Interval class in Joda-Time does not work with LocalDate, but Period does.

LocalDate start_a = new LocalDate( "1993-08-16" );
LocalDate stop_a = new LocalDate( "2014-09-09" );
Period period_a = new Period( start_a , stop_a );

LocalDate start_b = new LocalDate( "1995-02-14" );
LocalDate stop_b = new LocalDate( "2001-05-18" );
Period period_b = new Period( start_b , stop_b );

Period periodCombined = period_a.plus( period_b );
Period periodCombinedNormalized = periodCombined.normalizedStandard(); // Assumes that all years are 12 months, all weeks are 7 days, all days are 24 hours, all hours are 60 minutes and all minutes are 60 seconds. Not true for Daylight Saving Time and other anomalies.

Pretty-Print

If you want the output spelled out, use the DateTimeFormatterBuilder class. Use code such as this:

DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
 .appendMonthOfYearText()
 .appendLiteral(' ')
 .appendYear(4, 4)
 .toFormatter();

Search StackOverflow for many examples of using that class.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154