简体   繁体   English

Java 将自定义日期格式化为 MySQL DATETIME

[英]Java Format Custom Date to MySQL DATETIME

I have a String with a value in the format: 01-Jul-2011 12:52:00.我有一个字符串,其值的格式为:01-Jul-2011 12:52:00。

I would like to format this to be inserted into a MySQL database with the type as DATETIME.我想将其格式化为插入到类型为 DATETIME 的 MySQL 数据库中。

I realise that I need to get it in the form 01-07-2011 12:52:00 but I can't figure out how to do this.我意识到我需要以 01-07-2011 12:52:00 的形式获取它,但我不知道该怎么做。

Any solutions?有什么解决办法吗?

@Jigar is correct, if not terse. @Jigar 是正确的,如果不是简洁的话。 But it looks like you might need more info, and I'm going to spoonfeed it to you.但看起来你可能需要更多信息,我会用勺子喂给你。

Firstly, you shouldn't be trying to format a date to suit mysql.首先,您不应该尝试格式化日期以适应 mysql。 You should be passing a Date as a parameter to your sql query (not building up a String of sql).您应该将 Date 作为参数传递给您的 sql 查询(而不是构建 SQL 字符串)。

To parse the date from your input, try code like this:要从您的输入中解析日期,请尝试如下代码:

public static void main(String[] args) throws Exception {
    String input = "01-Jul-2011 12:52:00";
    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    Date date = format.parse(input);
    System.out.println(date); // "Fri Jul 01 12:52:00 EST 2011"
}

Here's an example of how you make sql calls using a JDBC connector passing parameters:下面是一个示例,说明如何使用 JDBC 连接器传递参数进行 sql 调用:

Date date = format.parse(input);
jdbcConnection.createStatement().execute("insert into mytable (id, some_date) values (?, ?)", new Object[]{1, date});

You don't need to worry about how to format the date for mysql - let the JDBC driver do that for you.您无需担心如何格式化 mysql 的日期 - 让 JDBC 驱动程序为您完成。

I suppose you mean you need to get the form "2011-07-01 12:52:00"? Here is a some example to convert between the two date representations:

String input = "01-Jul-2011 12:52:00";
java.util.Locale locale = new java.util.Locale("EN", "gb");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MMMM-yy HH:mm:ss", locale);
try
{
    java.util.Date date = sdf.parse(input);
    java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
    String output = sdf2.format(date);
    System.out.println("input: " + input + "\noutput: " + output);
}
catch (java.text.ParseException e)
{
    // error handling goes here
    e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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