Home > front end >  Covert Mon Sep 12 19:48:19 IST 2022 to 2022-09-12 00:00:00.0
Covert Mon Sep 12 19:48:19 IST 2022 to 2022-09-12 00:00:00.0

Time:09-15

I have one Date object which has value:- Mon Sep 12 19:48:19 IST 2022

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, -2);
Date fDate = calendar.getTime();

//Output of above code Mon Sep 12 19:48:19 IST 2022
Now I want to get this output like 2022-09-12 00:00:00.0 format

CodePudding user response:

I think it's the parse that's producing that output. Also, your format string is 'dd-MM-yyyy', and it looks like you want it to be yyyy-MM-dd.

Try this (omit the parse):

Date fDate = dateFormat.format(calendar.getTime()));

Hope this helps!

CodePudding user response:

Create a method which truncate the date. You can use ZoneDateTime::truncateTo.

private Date truncateToDays(Date date) {
    Instant instant = date.toInstant();
    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
    ZonedDateTime truncatedZonedDateTime = zonedDateTime.truncatedTo(ChronoUnit.DAYS);
    Instant truncatedInstant = truncatedZonedDateTime.toInstant();
    return Date.from(truncatedInstant);
}

Then you can convert your truncated date to the desired format:

DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
String strDate = myDateFormat.format(truncateToDays(fDate));

System.out.println(strDate);
// output: 2022-09-12 00:00:00.0
  • Related