0

i have a simple method to convert dates

private static SimpleDateFormat uiSDF = new SimpleDateFormat("MMM dd, yyyy hh:mm a");

try {
        
        System.out.println("DATE1 " + date);
        String abc1 = uiSDF.format(date);
        System.out.println("DATE2 " + abc1);
        Date abc2 = uiSDF.parse(abc1);
        System.out.println("DATE3 " + abc2);
        return uiSDF.parse(uiSDF.format(date));
    } catch (ParseException e) {
        System.out.println(DateConverter.class.getName() + " convertDBTimeStampToUIDate :" + e);
        e.printStackTrace();
        return null;
    }

convert the date to a string with a new format and convert that string into a date. issue is the .parse returns back the format to its original.

DATE1 Fri Oct 09 21:11:40 SGT 2020   
DATE2 Oct 09, 2020 09:11 PM
DATE3 Fri Oct 09 21:11:00 SGT 2020

DATE3 sysout should be same as DATE2 since i used the same uiSDF simpledateformat. Any idea why is reverting back to original date format?

Arnold Cristobal
  • 843
  • 2
  • 16
  • 36
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Oct 10 '20 at 04:58
  • You are not parsing the second's part in the format, you should use format like `MMM dd, yyyy hh:mm:ss a` – Eklavya Oct 10 '20 at 05:02
  • You're not changing the time zone's in anyway and `Date#toString` will make use of the systems timezone information to represent the date - `Date` DOES NOT carry ANY concept of formatting, nor can you (realistically) change the how the `toString` method treats it. This is WHY there is a `DateTimeFormatter` class, to seperate the concept of "time" from the concept of "output" – MadProgrammer Oct 10 '20 at 05:06

0 Answers0