[英]How to convert a string to date format in java?
How to convert a String to DateFormat
in java? 如何在Java中将字符串转换为
DateFormat
?
I am writing a application where I want to convert a string "20050105000200" to "2005-01-05 00:02:00". 我正在编写一个应用程序,要将字符串“ 20050105000200”转换为“ 2005-01-05 00:02:00”。 Is there a direct way to do it in Java?
用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
解析输入日期,然后再次使用格式格式化输出
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 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 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);
您可以使用simpledateformat类来执行此操作
Use SimpleDateFormat
. 使用
SimpleDateFormat
。 Haven't tried on my IDE, but it goes something like this: 尚未在我的IDE上尝试过,但是它是这样的:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.