字符串转换成日期异常

问题描述:字符串转换成日期异常

解决方案:SimpleDateFormat构造函数的样式与dateString的样式必须相符

关键点:String dateString = "2018-12-04";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

正确代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

	public static void main(String[] args) {

		String dateString = "2018-12-04";
		Date d = stringToDate(dateString);
		System.out.println(d);
	}
    /**
     * 字符串转换成日期
     * @param dateString
     * @return
     */
    private static Date stringToDate(String dateString){

        if(!"".equals(dateString) && dateString != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = sdf.parse(dateString);
            } catch (ParseException e) {
                System.out.println(e);
            }
            return date;
        }
        return null;
    }
}

打印信息:

Tue Dec 04 00:00:00 CST 2018

异常代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

	public static void main(String[] args) {

		String dateString = "2018-12-04";
		Date d = stringToDate(dateString);
		System.out.println(d);
	}
    /**
     * 字符串转换成日期
     * @param dateString
     * @return
     */
    private static Date stringToDate(String dateString){

        if(!"".equals(dateString) && dateString != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = sdf.parse(dateString);
            } catch (ParseException e) {
                System.out.println(e);
            }
            return date;
        }
        return null;
    }
}

异常信息:

java.text.ParseException: Unparseable date: "2018-12-04"
null

 

你可能感兴趣的:(后端)