public Date stringToDate(String myDateStr)
    {
        myDateStr = formatDateString(myDateStr);
        String sFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(sFormat);
        Date d = null;
        try
        {
            d = sdf.parse(myDateStr);
        }
        catch(ParseException pe)
        {
            log.error("Parse data from string error!" + pe.getMessage());
        }
        return d;
    }    public Date stringToDatetime(String myDateStr)
    {
        myDateStr = formatDateString(myDateStr);
        myDateStr = myDateStr.substring(19);
        String sFormat = "yyyy-MM-dd hh:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(sFormat);
        Date d = null;
        try
        {
            d = sdf.parse(myDateStr);
        }
        catch(ParseException pe)
        {
            log.error("Parse date from string error!" + pe.getMessage());
        }
        return d;
    }    public String dateToString(Date myDate)
    {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        return sf.format(myDate);
    }    public String datetimeToString(Date myDate)
    {
//        log.debug(myDate.toString());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sf.format(myDate);
    }

解决方案 »

  1.   

    /**
     * 将字符串类型日期格式化为Date类型的日期
     * <p>支持以下十种格式:<br>
     * <br>yyyyMMdd;
     * <br>yyyy/MM/dd&pound;¨yyyy/M/d&pound;&copy;&pound;&copy;;
     * <br>yyyy-MM-dd&pound;¨yyyy-M-d&pound;&copy;&pound;&copy;;
     * <br>yyyyMMdd HH:mm:ss;
     * <br>yyyy/MM/dd HH:mm:ss&pound;¨yyyy/M/d HH:mm:ss&pound;&copy;;
     * <br>yyyy-MM-dd HH:mm:ss&pound;¨yyyy-M-d HH:mm:ss&pound;&copy;;
     * @param datestr 字符串格式日期
     * @return Date类型日期
     */
    public static Date toDate(String datestr) {
    SimpleDateFormat sdf = null;
    int datetype = 0;
    boolean timetype = false;
    if (datestr.indexOf("-") > 0) {
    datetype = 1;
    } else if (datestr.indexOf("/") > 0) {
    datetype = 2;
    }
    if (datestr.indexOf(":") > 0) {
    timetype = true;
    }
    try {
    switch (datetype) {
    case 0 :
    {
    if (timetype) {
    sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    } else {
    sdf = new SimpleDateFormat("yyyyMMdd");
    }
    };
    break;
    case 1 :
    {
    if (timetype) {
    sdf = new SimpleDateFormat("yyyy-M-d HH:mm:ss");
    } else {
    sdf = new SimpleDateFormat("yyyy-M-d");
    }
    };
    break;
    case 2 :
    {
    if (timetype) {
    sdf = new SimpleDateFormat("yyyy/M/d HH:mm:ss");
    } else {
    sdf = new SimpleDateFormat("yyyy/M/d");
    }
    }
    }
    return sdf.parse(datestr);
    } catch (ParseException pe) {
    pe.printStackTrace();
    }
    return null;
    }