Search code examples
javadatesimpledateformatdate-formatting

Java wrong data format transformation


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?


Solution

  • 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);