关于Java中的Date类

时间:2019-07-05 20:43:53

标签: java

每当我向程序提供不同的日期时,总是将输出作为错误的日期。它显示上一年的12月月份日期。

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();
        }
    }
}

运行:

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)

2 个答案:

答案 0 :(得分:1)

我认为问题在于年份模式。请尝试以下操作:

  Date d1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(v[0]);

答案 1 :(得分:1)

您应将小写的yyyy用作“年份”。大写字母Y代表“星期”,请参见How does Java "week year" really work?