如何转换日期来自" Tue May 08 2018 13:15:00"到" 2018-05-08 13:15:00.000"在java中

时间:2018-05-28 11:41:22

标签: java date sqldatetime java-date

如何在java中将日期从"Tue May 08 2018 13:15:00"转换为"2018-05-08 13:15:00.000",因为我必须将它用于自定义sql查询中的where子句ex TO_timestamp('2018-05-08 13:15:00.000', 'YYYY-MM-DD HH24:MI:SS.FF')

3 个答案:

答案 0 :(得分:1)

我想我有一个建议,试图解决你的问题......

注意:由于String中日期的转换,您可能必须配置SimpleDateFormat的Locale。否则将抛出异常 java.text.ParseException

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

public class Test {

    public static void main(String[] args) {

        try {
            String dateStr = "Tue May 08 2018 13:15:00";

            SimpleDateFormat sdfBefore = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
            SimpleDateFormat sdfAfter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

            Date date = sdfBefore.parse(dateStr);

            System.out.println(sdfAfter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

我希望我能帮到你。

答案 1 :(得分:1)

首先你需要解析你的字符串:

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("EEE MMM dd uuuu H:mm:ss", Locale.ENGLISH);
    String dateTimeString = "Tue May 08 2018 13:15:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
    System.out.println(dateTime);

打印

  

2018-05-08T13:15

正如评论中所说,不要将字符串传输到您的数据库。假设您至少使用Java 8且至少使用JDBC 4.2,只需通过LocalDateTime将解析后的PreparedStatement对象提供给数据库,例如:

    PreparedStatement queryStatement = yourDbConnection.prepareStatement(
            "select * from your_table where your_column = ?");
    queryStatement.setObject(1, dateTime);

我假设您的字符串和数据库的来源同意应该在哪个时区解释日期和时间。在大多数情况下,您应该更明确地了解时区。

对于任何阅读并且需要像2018-05-08 13:15:00.000这样的字符串的人来说,除了数据库查询以外的其他目的,获取此格式的方法是通过另一个格式化程序:

    DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    String formattedDateTimeString = dateTime.format(targetFormatter);
    System.out.println(formattedDateTimeString);

打印

  

2018-05-08 13:15:00.000

链接: The Java™ Tutorials: Trail: Date Time解释了如何使用现代Java日期和时间API java.time

答案 2 :(得分:1)

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Test {

    public static void main(String[] args) {

        String dateStr = "Tue May 08 2018 13:15:00";
        DateTimeFormatter formatterFrom = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss");
        LocalDateTime localDate = LocalDateTime.parse(dateStr, formatterFrom);

        DateTimeFormatter formatterTo = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        String localDate1 = formatterTo.format(localDate);

        System.out.println(localDate1); // 2018-05-08 13:15:00.000

    }

}
相关问题