简体   繁体   中英

How to convert a string to date format in java?

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.

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

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

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

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

您可以使用simpledateformat类来执行此操作

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM