Liviu
Liviu

Reputation: 51

Java Date, string convert to Date Object

I have a question, how can I convert a string like 20130706123020 to a date object. So I what to convert the string 20130706123020 to a date object looking like:

2013-07-06 12:30:20

Attempted code:

String date = "20130706234310";
Date date1 = new SimpleDateFormat("yyyy-m-d H:m:s").parse(date);
System.out.println(date1);

Any suggestions will be appreciated.

Thank you!

Upvotes: 1

Views: 280

Answers (3)

pouyan
pouyan

Reputation: 3439

use this :

long int my_date = 20130706123020L

and after that :

String date_Text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(my_date));

Upvotes: 1

user000001
user000001

Reputation: 33317

Use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); 
Date date = sdf.parse("20130706123020");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

System.out.println(sdf2.format(date));

Upvotes: 1

JHS
JHS

Reputation: 7871

You have to first parse the String using the parse method from SimpleDateFormat.

Then pass the Date object returned by the parse method to another SimpleDateFormat and then using the format method get the date in the format you want.

String s = "201307061230202";

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS"); // format in which you get the String
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // format in which you want the date to be in
System.out.println(sdf1.format(sdf.parse(s)));

The significance of HH, hh, KK and kk in the hour field is different. I have used HH you can use the one according to your requirement.

H   Hour in day (0-23)
k   Hour in day (1-24)
K   Hour in am/pm (0-11)
h   Hour in am/pm (1-12) 

Upvotes: 4

Related Questions