java - 在Java中解析日期时间格式并将其从csv文件转换为mysql

标签 java mysql datetime csv

我有一个 csv 文件,其中日期时间列以“DD-MM-YYYY HH:MM”格式定义。但问题是 MySQL 只接受日期时间类型“YYYY-MM-DD HH:MM”。我想将 csv 文件中给出的格式转换为 MySQL 定义的格式,但我无法做到这一点。我尝试在 excel 中隐藏格式,但首先 excel 中没有日期时间格式,如果我将列分成两部分,那么它改变了我的文件的结构,因此无法插入数据库。因此,唯一的选择是使用Java程序并在插入之前更改格式。 有人可以在这方面为我提供一些帮助吗?

这是我的类,它被要求转换格式,但我不知道这里出了什么问题,也不知道它是否足够,或者我遗漏了一些东西。(这个类正在从另一个程序访问。)

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

public class DateUtil {

    // List of all date formats that we want to parse.
    // Add your own format here.
    private static List<SimpleDateFormat> 
            dateFormats = new ArrayList<SimpleDateFormat>() {
        private static final long serialVersionUID = 1L; 
        {
//            add(new SimpleDateFormat("M/dd/yyyy"));
//            add(new SimpleDateFormat("dd.M.yyyy"));
//            add(new SimpleDateFormat("M/dd/yyyy hh:mm:ss a"));
//            add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a"));
//            add(new SimpleDateFormat("dd.MMM.yyyy"));
            add(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
            add(new SimpleDateFormat("yyyy-MM-dd hh:mm"));
        }
    };

    /**
     * Convert String with various formats into java.util.Date
     * 
     * @param input
     *            Date as a string
     * @return java.util.Date object if input string is parsed 
     *          successfully else returns null
     */
    public static Date convertToDate(String input) {
        Date date = null;
        if(input == null ) {
            return null;
        }
        for (SimpleDateFormat format : dateFormats) {
            try {
                format.setLenient(false);
                date = format.parse(input);
            } catch (ParseException e) {
                //Shhh.. try other formats
            }
            if (date != null) {
                break;
            }
        }

        return date;
    }

}

最佳答案

下面是如何通过 SimpleDateFormat 类更改格式的示例。

public static String dateConvert(String origFormat) throws ParseException {
    SimpleDateFormat origDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    Date retrivedDate = origDateFormat.parse(origFormat);
    return newDateFormat.format(retrivedDate);
}

关于java - 在Java中解析日期时间格式并将其从csv文件转换为mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015428/

相关文章:

mysql - SQL语句 "for each state with more than 20 members whose first name start with “D”。”?

java - 使用 Java DateTimeFormatter 解析 PDF 日期

java.sql.SQLSyntaxErrorException : Columns of type 'INTEGER' cannot hold values of type 'CHAR'

java - @Override 和 super

java - 将我的客户端 PC 重定向到默认登录页面

Java - 使用数组作为参数实例化对象

mysql - 嵌套集过滤

mysql - 无法使用命令行安装 craft3。测试数据库凭据...失败:

Excel - 将以 Z 结尾的 ISO8601 日期转换为适合输入类型为 'timestamp with time zone' 的 Postgres 字段的格式

javascript - 减去日期时间值