-1

I have picked up a date from date picker and another from currently system time. when I want to subtract 2 date what one of them is before 2000 I get some invalid answer for year. how can I resolve it?

public class Duration {
    private int year,month,day,hour,min,seconds;

    public Duration(long endTime, long startTime){
        Calendar calendar1=new GregorianCalendar();
        calendar1.setTimeInMillis(endTime);
        Calendar calendar=new GregorianCalendar();
        calendar.setTimeInMillis(startTime);
        this.year=calendar1.get(Calendar.YEAR)-calendar.get(Calendar.YEAR);
        this.month=calendar1.get(Calendar.MONTH)-calendar.get(Calendar.MONTH);
        this.day=calendar1.get(Calendar.DAY_OF_MONTH)-calendar.get(Calendar.DAY_OF_MONTH);
        this.hour=calendar1.get(Calendar.HOUR)-calendar.get(Calendar.HOUR);
        this.min=calendar1.get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);
        this.seconds=calendar1.get(Calendar.SECOND)-calendar.get(Calendar.SECOND);
        System.out.println(toString());
    }

    public int getDay() {
        return day;
    }

    public int getHour() {
        return hour;
    }

    public int getMin() {
        return min;
    }

    public int getMonth() {
        return month;
    }

    public int getSeconds() {
        return seconds;
    }

    public int getYear() {
        return year;
    }

    @Override
    public String toString() {
        return year+" "+month+" "+day+" "+hour+" "+min+" "+seconds;
    }
}

when I want to subtract a date in 1998/2/jan from current time I get this result :

-1879 1 3 10 24 34

what the year isn't correctly.

  • 3
    Please search. There are hundreds of answers already on how to calculate the difference between dates. – Ole V.V. Feb 04 '19 at 06:59
  • yes but no one of them works for before 2000 – Ali Azizi Pour Feb 04 '19 at 07:06
  • Hundreds of incorrect answers? I seriously doubt it. – Ole V.V. Feb 04 '19 at 07:59
  • I recommend you don’t use `Calendar`. That class is poorly designed and long outdated. Instead use for example `ZonedDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 04 '19 at 08:19
  • I cannot reproduce. `new Duration(883_699_200_000L, System.currentTimeMillis())` prints `-21 -1 -2 -8 -22 -31`, which appears to me to be correct. Your problem is not in the code you have posted, it is somewhere else. Could you provide a reproducible example, please? [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Ole V.V. Feb 04 '19 at 08:24
  • 1
    Rather than rolling your own `Duration` class consider using one from a library. [`PeriodDuration`](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/PeriodDuration.html) from [ThreeTen Extra](https://www.threeten.org/threeten-extra/) seems to be the obvious choice. – Ole V.V. Feb 04 '19 at 08:50
  • 1
    [I downvoted because lacking an MCVE makes it hard to answer](https://idownvotedbecau.se/nomcve/) and because your code works fine also for years before 2000, so there is no real question here. – Ole V.V. Feb 04 '19 at 08:59
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 04 '19 at 21:39

3 Answers3

1
LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

You will get the number of days in long format. Also refer this answer by Mark Byers.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Abraham Mathew
  • 2,029
  • 3
  • 21
  • 42
1

Method: 1

 try {
    DateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    Date date1 = new java.util.Date();
    Date date2 = df.parse("04-02-2019 12:00:00");
    long diff = date2.getTime() - date1.getTime();

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(diff);
    int year = cal.get(Calendar.YEAR);
    Log.e("Diff Year" , year+ " --" + diff);
    Log.e("Diff Value" , date1.getTime() + " -- " + date2.getTime() + " --" + diff);

} catch (ParseException e){
    Log.e("Diff Value", "Exception", e.getMessage().toString());
}

Method: 2

LocalDate d1 = LocalDate.parse("2017-04-02", 
DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-04-04", 
DateTimeFormatter.ISO_LOCAL_DATE);
Duration dateDifference = Duration.between(d1.atStartOfDay(), 
d2.atStartOfDay());
long dayDifference = dateDifference.toDays();
  • Subtract Two dates and add difference value in Calendar Object and retrieve Year value from its Object.
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Feb 04 '19 at 08:28
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 04 '19 at 21:40
0

tl;dr

LocalDate               // Represent a date-only value, without time-of-day and without time zone.
.of( 1999 , 1 , 23 )    // Use factory methods to instantiate rather than constructors, in the *java.time* classes.
.minusWeeks( 12 )       // Do date-math with `plus…` and `…minus` methods.
.toString()             // Generate text as a `String` object with text representing the date value in standard ISO 8601 format: YYYY-MM-DD

See this code run live at IdeOne.com.

1998-10-31

Avoid legacy date-time classes

Never use Calendar or Date classes. Those terrible classes were supplanted years ago by the java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

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.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-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 ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Period

To represent a span-of-time in terms of years-months-days, use Period.

Period p = Period.ofDays( 5 ) ;

Date-time math

You can perform addition and subtraction of date-time values in java.time by calling the plus… and minus… methods.

LocalDate later = ldt.plus( p ) ;

Duration

If you want to represent a span-of-time in terms of days (24-hour chunks of time, unrelated to calendar), hours, minutes, seconds, and fractional second, use Duration.

Year

Your question not clear, but seems to be about the year 2000. There is nothing special about that year with the java.time classes.

You can interrogate the java.time classes for their year value.

int year = ld.getYear() ;
if( year < 2000 ) { … }

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.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

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.

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