无法转换数据类型

问题描述

| 在我的
customerInfoForm
中,我有一个字段
String DateOfBirth
。 在我的
Customer
类中,
DateOfBirth
DateTime
类型。 在
DataBase
中,列类型也是
DateTime
。 当我呼叫
customer.setDateOfBirth(customerInfoForm.getDateOfBirth);
显示错误。如何转换? 请建议该怎么办?     

解决方法

您需要一个“ 8”对象将字符串版本解析为日期。
DateFormat format = new SimpleDateFormat(\"yyyyMMdd\");
customer.setDateOfBirth(format.parse(customerInfoForm.getDateOfBirth()));
注意,您谈论的不是“ 4”,它不是日期的核心Java对象。如果您正在使用其他库(例如joda-time),则需要使用其他格式化程序。     ,客户中有一个setDateOfBirth的重载方法,该方法可以接受String并将DateOfBirth设置为DateTime。     ,
public Date getDate(String dateString,String format) {
                        Date toReturn=null;     
                        try {
            SimpleDateFormat dFormat = new SimpleDateFormat(format);
            toReturn= dFormat.parse(dateString);
            return toReturn;
        } catch (Exception e) {         
            return null;
        }
    }
使用此函数可以将String格式的Date转换为Date对象。确保您传递正确的格式。 例如。格式(
\"MM/dd/yy HH:mm a\"
等)