-4

I need a Java program that subtracts 5 years from the current year. Everything is working fine but after I run the program:

DateFormat dateFormat = new SimpleDateFormat("yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR,-5);
Date today = new Date();
String start = dateFormat.format(cal.getTime()).toString();
String end = dateFormat.format(today).toString();
double start_doub = Double.parseDouble(start);
double end_doub = Double.parseDouble(end);
System.out.println(start_doub);
System.out.println(end_doub);

The result is:

2012.0
2017.0

I don't know the reason why the program adds .0 after the year? How can I remove the last part?

adama
  • 537
  • 2
  • 10
  • 29
  • 5
    Use `int` instead of `double` –  Oct 23 '17 at 13:18
  • 2
    How can a year be a double? – Jens Oct 23 '17 at 13:19
  • 1
    Okay, this was my mistake, after you suggested to use integer instead of double I know the reason. Thank you! – adama Oct 23 '17 at 13:22
  • 4
    If you are using Java 8 or 9 this is much easier using the `Year` class from the new date/time support. – greg-449 Oct 23 '17 at 13:25
  • 1
    Don’t use strings to extract a year. You already have a Calendar object. Use `cal.get(Calendar.YEAR)` to get the year. – VGR Oct 23 '17 at 14:09
  • 2
    Use modern java.time classes instead. `Year.now( ZoneId.of( "Africa/Casablanca" ) ).minusYears( 5 )` – Basil Bourque Oct 23 '17 at 14:34
  • 2
    Even if you insist on using the old and outdated classes — which I strongly discourage — you are overcomplicating things. You just need a `Calendar`. You can still do without `DateFormat`, `SimpleDateFormat` and `Date`. – Ole V.V. Oct 23 '17 at 17:51

1 Answers1

0

Your code look like below

        DateFormat dateFormat = new SimpleDateFormat("yyyy");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR,-5);
        Date today = new Date();
        String start = dateFormat.format(cal.getTime()).toString();
        String end = dateFormat.format(today).toString();
        int start_doub = Integer.parseInt(start);
        int end_doub = Integer.parseInt(end);
        System.out.println(start_doub);
        System.out.println(end_doub);
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Zenith
  • 1,037
  • 1
  • 10
  • 21