简体   繁体   English

将字符串转换为日期类型

[英]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: 以下是一些提示:

  • Make sure that you are including the correct imports. 确保包含正确的导入。 Depending on what is in your classpath, you may have accidentally imported java.sql.Date or some other rogue import. 根据类路径中的内容,您可能不小心导入了java.sql.Date或其他一些恶意导入。
  • Try printing the contents of birthDate before entering the try block and verify that it really contains a string of format dd-MMM-yyyy 在进入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());
        }
    }
}

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.

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