Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a date to dd.MM.yyyy format in Java? [duplicate]

Tags:

java

date

jdk6

How can I convert the date(Mon Jan 12 00:00:00 IST 2015) in the format MM.dd.yyyy or dd.MM.yyyy?

I tried using the below approach

    String dateStr = "Mon Jan 12 00:00:00 IST 2015";

    DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    System.out.println(formatter.format(dateStr));

but got,

Exception in thread "main" java.lang.IllegalArgumentException: 
Cannot format given Object as a Date
like image 278
Farhan Shirgill Ansari Avatar asked Jan 17 '26 06:01

Farhan Shirgill Ansari


2 Answers

You have to parse the string to Date then format that Date

String dateStr = "Mon Jan 12 00:00:00 IST 2015";

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(formatter1.format(formatter.parse(dateStr)));

Demo

like image 146
singhakash Avatar answered Jan 19 '26 20:01

singhakash


String dateStr = "Mon Jan 12 00:00:00 IST 2015";

First you have to parse your string to a date:

DateFormat parser = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = parser.parse(dateStr);

and then you can format it:

DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(formatter.format(date));
like image 25
Jens Avatar answered Jan 19 '26 18:01

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!