1

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!

7
  • what did you try so far? Commented Jul 6, 2013 at 20:56
  • I have tried but I got the following error: java.text.ParseException: Unparseable date: "20130706234310" Commented Jul 6, 2013 at 20:56
  • i tried the SimpleDateFormat and DateTimeFormat Commented Jul 6, 2013 at 20:57
  • Post your attempted code, one of those date libs only Commented Jul 6, 2013 at 20:58
  • 1
    @Liviu Don't post your code as comment (it is hard to read). Instead add it to your question using [edit] option (right under your question) Commented Jul 6, 2013 at 21:07

3 Answers 3

4

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) 
Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

1

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));

3 Comments

This does not compile... error: integer number too large: 20130706123020
are you using "Long int " ?
Yes, if you change it to long my_date = 20130706123020L; it compiles. It looks like the compiler wants to interpret the number as an int if you omit the L in the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.