javaandroidsimpledateformatdatetime-formatdayofmonth

How to decode the date in Android? - DATETIMESTAMP


The following code gave me Datetimestamp as [ 2020-07-183 17:07:55.551 ]. The issue is with "Day" in Datetimestamp, which has three digits. How to format currentTimeMillis into the right format for day of month?

 public String Datetimesetter(long currentTimeMillis, SimpleDateFormat dateFormat) {
        
        dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS.SSS");
        // Create a calendar object that will convert the date and time value in milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(currentTimeMillis);
        return dateFormat.format(calendar.getTime());
    }

SOLUTION WHICH WORKED FOR ME:

Please visit this link.


Solution

  • This is for the case you are supporting Apps from API level 26 (native support of java.time) or you are willing / allowed to use a backport library of the same functionality.

    Then you can use a correct / matching pattern (one that considers three-digit days) like this:

    public static void main(String[] args) {
        // mock / receive the datetime string
        String timestamp = "2020-07-183 17:07:55.551";
        // create a formatter using a suitable pattern (NOTE the 3 Ds)
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-DDD HH:mm:ss.SSS");
        // parse the String to a LocalDateTime using the formatter defined before
        LocalDateTime ldt = LocalDateTime.parse(timestamp, dtf);
        // and print its default String representation
        System.out.println(ldt);
    }
    

    which outputs

    2020-07-01T17:07:55.551
    

    So I guess the day of year no. 183 was actually July 1st.