Convert a Date dd/MM/yyyy to dd-MM-yyyy in java

5.6k views Asked by At

I'm trying to convert a date in dd-MM-yyyy format from YYYY-MM-dd hh:mm:ss.ms in java using the below code but m unable to get the desired value

 String dob = (new SimpleDateFormat("dd-MM-yyyy")).format(customerEntity.getDob().toString());

customerEntity.getDob().toString is providing me this value 1987-06-12 00:00:00.0

But when i'm parsing it to the String dob it produces 163-06-1987 as the output whereas i want the output like 12-06-1987 .

Any help will be appreciable, thanks well in advance

2

There are 2 answers

4
PankajT On

Try parsing your string date into a Date first in format it is coming. Post that pass on that Date object to a format in the format you want your output.

As in below :

    Date dob = (new SimpleDateFormat("yyyy-MM-dd")).parse("1987-06-12 00:00:00.0");
    String dob1 = (new SimpleDateFormat("dd-MM-yyyy")).format(dob);
0
andolsi zied On

format method in SimpleDateFormat take a Date as argument and not a String

public static void main(String[] args) {
 String dateStr = "29/12/2016";
 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
 try {
  Date date = sdf.parse(dateStr);
  sdf = new SimpleDateFormat("dd-MM-yyyy");
  System.out.println(sdf.format(date));
 } catch (ParseException e) {
  e.printStackTrace();
 }
}