-3

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

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Mavericks
  • 283
  • 1
  • 7
  • 20

2 Answers2

1

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();
 }
}
andolsi zied
  • 3,553
  • 2
  • 32
  • 43
0

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);
PankajT
  • 145
  • 3
  • Pankaj it's working fine for the static String but can you tell me how to parse the value of an object like mentioned in the Code, i'm parsing the date of bearth by an Object, customer.getDOB(); – Mavericks Dec 29 '16 at 10:23
  • As you said, customerEntity.getDob().toString is providing me this value 1987-06-12 00:00:00.0. – PankajT Dec 29 '16 at 10:26
  • PankajT it's just because i'm typecasting the ObjectValue in String using toString() method, but for now in order to Convert this DOB in String all i'm doing is this – Mavericks Dec 29 '16 at 10:31
  • PankajT it's just because i'm typecasting the ObjectValue in String using toString() method, but for now in order to Convert this DOB in String all i'm doing is this String dob = (new SimpleDateFormat("dd-MM-yyyy")).format(customerEntity.getDob()); – Mavericks Dec 29 '16 at 10:32