将字符串转换为日期类型 [英] convert string to date type
本文介绍了将字符串转换为日期类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将字符串转换为日期格式,但以下方式无效。
I want to convert string to date format, but the following way didn't work.
它为出生
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
以下是一些提示:
- 确保您包含正确的导入。根据
您的类路径中的什么,您可能会意外导入
java.sql.Date或其他一些流氓进口。 - 尝试在进入try块之前打印birthDate的内容
,并确认它真的是
包含格式的字符串dd-MMM-yyyy
-
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());
}
}
}
这篇关于将字符串转换为日期类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文