-1

How to convert a String to DateFormat in java?

I am writing a application where I want to convert a string "20050105000200" to "2005-01-05 00:02:00". Is there a direct way to do it in Java? I want both input and output in String. Please let me know if there is a way to do it directly.

Can you give me some simple codes?

Thanks.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Aritra
  • 163
  • 4
  • 18
  • 2
    This would be more hassle than it's worth. Just store the date in a general format (unix time, rfc, etc.). – Evan Mulawski Jan 25 '12 at 12:23
  • http://stackoverflow.com/q/8292105/584420 – James Jithin Jan 25 '12 at 12:26
  • 1
    *"Can U give me some smple codes?"* SO is not a code generation machine. *"Thanks."* Your appreciation would be better expressed by typing all 3 letters of words like 'you'. – Andrew Thompson Jan 25 '12 at 12:29
  • my mistake sorry because im new to java and this forum – Aritra Jan 25 '12 at 12:46
  • 1
    @Aritra - This question has been asked so many times on SO (apart from its simplicity) that I wonder if you did any previous investigation at all. Stack Overflow's rules of conduct request that you do so before posting questions, as to avoid asking the same question over and over again. – lsoliveira Jan 25 '12 at 12:49

6 Answers6

4

You can use SimpleDateFormat to parse the input date, and then again to format the output

SimpleDateFormat inFmt = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat outFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = inFmt.parse("20050105000200");
System.out.println(outFmt.format(d));
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
1

You should first parse it to a date like this:

http://www.exampledepot.com/egs/java.text/parsedate.html

and then format it again like this:

http://www.exampledepot.com/egs/java.text/formatdate.html

nwaltham
  • 2,067
  • 1
  • 22
  • 40
1

This example might help you

   String str_date="11-June-07";
 DateFormat formatter ; 
 Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date);  
Vinay
  • 6,891
  • 4
  • 32
  • 50
1

Use a DateFormat to parse() this String to a Date object. Use a different DateFormat to format() the Date to the String representation you want.

See this

Frankline
  • 40,277
  • 8
  • 44
  • 75
0

You can use simpledateformat class for doing that

nidhin
  • 6,661
  • 6
  • 32
  • 50
0

Use SimpleDateFormat. Haven't tried on my IDE, but it goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String reformattedStr = myFormat.format(fromUser.parse("20050105000200"));
System.out.println(reformattedStr);
Marcelo
  • 4,580
  • 7
  • 29
  • 46