[英]convert string to date type
I want to convert string to date format, but the following way didn't work. 我想将字符串转换为日期格式,但以下方式不起作用。
It yields null
for birth
. 它的
birth
null
。
Date birth;
try {
DateFormat formatter ;
formatter = new SimpleDateFormat("dd-MMM-yyyy");
birth = (Date)formatter.parse(birthDate); // birtDate is a string
} catch (ParseException e) {
System.out.println("Exception :"+e);
}
Your answer is right on the money. 你的答案是正确的钱。 I put it in a full program and tested it.
我把它放在一个完整的程序中并进行测试。
It now prints out 它现在打印出来了
Default date format Fri Mar 30 00:00:00 CDT 2012
Our SimpleDateFormat 30-Mar-2012
Our SimpleDateFormat with all uppercase 30-MAR-2012
Here are some tips: 以下是一些提示:
- -
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BirthDate {
public static void main(String[] args) {
Date birth = null;
String birthDate = "30-MAR-2012";
DateFormat formatter = null;
try {
formatter = new SimpleDateFormat("dd-MMM-yyyy");
birth = (Date) formatter.parse(birthDate); // birtDate is a string
}
catch (ParseException e) {
System.out.println("Exception :" + e);
}
if (birth == null) {
System.out.println("Birth object is still null.");
} else {
System.out.println("Default date format " + birth);
System.out.println("Our SimpleDateFormat " + formatter.format(birth));
System.out.println("Our SimpleDateFormat with all uppercase " + formatter.format(birth).toUpperCase());
}
}
}
Your code works fine. 你的代码运行正常。 If you care to use Joda Time you can use this.
如果你想使用Joda Time,你可以使用它。 You can go through the documentation to unleash the complete functionality in case you plan to use the time for DB testing and stuff.
如果您打算使用时间进行数据库测试和填充,您可以浏览文档以释放完整的功能。
import org.joda.time.DateTime;
DateTime dt = new DateTime("YYYY-MM-DD");//new DateTime("2012-03-30")
System.out.println(dt);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.