SimpleDateFormat. format returning wrong date

怎甘沉沦 提交于 2021-02-04 08:40:32

问题


I have this code I would like to know why it returns correct date

Festival f= (Festival) festival.get(0);
Date d=f.getSDate();


System.out.println(d.getYear());
System.out.println(d.getMonth());
System.out.println(d.getDate());


SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); // define your format.
String formattedDate = df.format(d);
System.out.println("New Date To Show::"+formattedDate);

the output is this

2019
2
27
New Date To Show::27/03/3919

回答1:


Try to use this :

   Date date=new Date(); 
   // you can assign your return from the function here



    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    System.out.println(localDate.getMonthValue());
    System.out.println(localDate.getDayOfMonth());
    System.out.println(localDate.getYear());


    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String formattedDate = df.format(date);
    System.out.println("New Date To Show::"+formattedDate);



回答2:


It's because the month (d.getMonth()) starts from zero and 2 is actually 3



来源:https://stackoverflow.com/questions/55395261/simpledateformat-format-returning-wrong-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!