-3

Whenever I am providing different date to the program it's always gives output as wrong date. Its showing the previous year December month date.

import java.text.*;
import java.util.*;

public class Sample {

    public static void main(String args[])throws Exception 
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the details");
        String str = s.nextLine();
        String v[] = str.split(",");

        System.out.println(v[0]);
        System.out.println(v[1]);
        System.out.println(v[2]);
        try{
            Date d1 = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").parse(v[0]);
            Date d2 = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").parse(v[1]);


            System.out.println(v[0]+"  =  "+ d1); 
            System.out.println(v[1]+"  =  "+d2); 
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

run:

Enter the details
06/05/2018 02:17:52,06/02/2015 03:15:33,Sourav
06/05/2018 02:17:52
06/02/2015 03:15:33
Sourav
06/05/2018 02:17:52  =  Sun Dec 31 02:17:52 IST 2017
06/02/2015 03:15:33  =  Sun Dec 28 03:15:33 IST 2014
BUILD SUCCESSFUL (total time: 3 seconds)
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 5
    Consider using `java.time` package. The classes you use are obsolete and hard to use. https://www.baeldung.com/java-8-date-time-intro – parsecer Jul 05 '19 at 20:49
  • Always **search Stack Overflow** thoroughly before posting. Learn from existing code examples, study how those match or differ from your own code. – Basil Bourque Jul 05 '19 at 22:08

2 Answers2

1

I believe the issue is with the year pattern. Try the following instead:

  Date d1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(v[0]);
toolkit
  • 49,809
  • 17
  • 109
  • 135
1

You should use lowercase yyyy for "year". Uppercase Y represents "week year", see How does Java "week year" really work?

Timekiller
  • 2,946
  • 2
  • 16
  • 16