如何将一系列字符转换为日期格式以存储在数据库中?

huangapple go评论90阅读模式
英文:

How to convert a sequence of characters into a date format to store in the database?

问题

基于文件名,我必须将字符串拆分成不同的元素数组,我已经能够从文件命名约定中提取出时间戳,现在我需要将此字符串转换为日期格式以存储到数据库表中:

示例:
字符串 20200913204839 需要转换为日期格式,如 13-Sep-2020 20:48:39(列名),并且 PL/SQL 代码块具有以下参数值,其格式为 列名-数据类型(varchar2)-插入语句中的值如下:

to_date(column_name, 'dd-mon-yyyy hh24:mi:ss')

这是等效的 MATLAB 代码:

fn.fntestdate = datestr(datenum(column_name, 'yymmddHHMM'), 'dd-mmm-yyyy HH:MM:SS')

我该如何在 Java 中实现相同的逻辑?

我尝试了几个使用 SimpleDateFormat 的函数来尝试解析它,但是收到了 "unparseable function" 错误。

我认为在解析之前,column_name 必须先转换为数字,然后再转换为日期?
在加载之前需要进行多次隐式转换。请为此提供最佳方法。

英文:

Based on the filename i have to break down the string into a different array of elements and i was able to extract the timestamp from the file naming convention and now i need to pass this string to a date format to be stored into the db tables:

Example:
20200913204839 string needs to be converted into date format as 13-sep-2020 20:48:39 (column_name) and the pl/sql block has the parameter value in this format column name-datatype (varchar2) -and value inside the insert statement as :

to_date(column_name,'dd-mon-yyyy hh24:mi:ss')

This is the equivalent matlab code:

 fn.fntestdate = datestr(datenum(column_name,'yymmddHHMM'),'dd-mmm-yyyy HH:MM:SS')

How do i incorporate the same logic in Java?

I tried several functions SimpleDateFormat trying to parse it,but was receiving "unparseable funcction" ERROR.

I think column_name has to be converted into number and then converted to date before parsing it?
Requires several multiple implicit conversions before loading. Suggest the best possible approach for this

答案1

得分: 1

这是与您的测试用例配合使用的示例:

import java.text.SimpleDateFormat;  
import java.util.Date;  
public class StringToDateExample1 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="20200913204839";  
        Date date1=new SimpleDateFormat("yyyyMMddhhmmss").parse(sDate1);  
        System.out.println(date1);
    }  
}

对于测试用例 20200913204839,它返回:

Sun Sep 13 20:48:39 UTC 2020

这是 SimpleDateFormat 中字符的含义:

  • yyyy 表示年份(示例:2020)
  • MM 表示月份(示例:7、8)
  • dd 表示月份中的天数(示例:15)
  • HH 表示一天中的小时数(示例:20)
  • mmss 分别表示分钟和秒数(示例:52:34)

它不一定非要是一个 Date 对象 - 只是一个 String 也可以。

是的,使用 SimpleDateFormat 完全没问题。

编辑:特定格式化

我已经根据您的情况进行了格式化:

import java.text.SimpleDateFormat;  
import java.util.Date;  
public class StringToDateExample1 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="20200913204839";  
        Date date1=new SimpleDateFormat("yyyyMMddhhmmss").parse(sDate1);
        String formatted = new SimpleDateFormat("dd-EE-yyyy hh:mm:ss").format(date1);
        System.out.println(formatted);
    }  
}

我们首先将字符串解析为日期,然后可以进行格式化。

测试用例 20200913204839 返回:

13-Sun-2020 08:48:39
英文:

Here's an example that works with your test cases:

import java.text.SimpleDateFormat;  
import java.util.Date;  
public class StringToDateExample1 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="20200913204839";  
        Date date1=new SimpleDateFormat("yyyyMMddhhmmss").parse(sDate1);  
        System.out.println(date1);
    }  
}  

With test case 20200913204839 it returns:

Sun Sep 13 20:48:39 UTC 2020

Here's what the characters in the SimpleDateFormat mean:

yyyy signifies a year (Example: 2020)

MM signifies a month (Example: July, August)

dd signifies a day in a month (Example: 15)

HH signifies an hour in a day (Example: 20)

mm and ss signify minutes and seconds respectively (Example: 52:34)

It doesn't have to be a Date - just a String works fine.

And yes - using SimpleDateFormat works just fine.

EDIT: Specific Formatting

I've formatted it specifically for your case:

import java.text.SimpleDateFormat;  
import java.util.Date;  
public class StringToDateExample1 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="20200913204839";  
        Date date1=new SimpleDateFormat("yyyyMMddhhmmss").parse(sDate1);
        String formatted = new SimpleDateFormat("dd-EE-yyyy hh:mm:ss").format(date1);
        System.out.println(formatted);
    }  
} 

We first parse the String into a date, from which we can format.

A test case 20200913204839 returns:

13-Sun-2020 08:48:39

答案2

得分: 1

> … 提出最佳方法建议

这正是我正在做的。 如何将一系列字符转换为日期格式以存储在数据库中?

java.time 和 JDBC 4.2

13-sep-2020 20:48:39 是一个不错的日期和时间。我想你是想表示一个时间点。这个时间点只在特定的时区内才有意义。因此,要存储一个时间点,需要将时间与时区(例如 Asia/Ust-Nera)或者与 UTC 的偏移(例如 +10:00)一起存储。由于你正在使用 Oracle 数据库:如果我得到的信息是正确的,Oracle 的 timestamp with time zone 数据类型(与其他关系型数据库管理系统不同)的含义就是字面意思:带有时区的时间戳。因此,你应该能够将 Java 的 ZonedDateTime 转换为它。就这么做。

首先,解析字符串:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
ZoneId zone = ZoneId.systemDefault();

String dateTimeFromFileName = "20200913204839";

ZonedDateTime dateTime = LocalDateTime.parse(dateTimeFromFileName, formatter)
        .atZone(zone);
System.out.println("解析后的日期时间:" + dateTime);

到目前为止的输出是在我的时区内:

> 解析后的日期时间:2020-09-13T20:48:39+02:00[Europe/Copenhagen]

我使用了 JVM 的默认时区。如果可以的话,可以使用 地区/城市 格式来指定一个时区,例如:

ZoneId zone = ZoneId.of("Asia/Ust-Nera");

其次,传递给一个预期接受 timestamp with time zone 的 PL/SQL 块(由于我手头没有 Oracle 数据库,所以没有测试过):

CallableStatement stmt = yourDatabaseConnection
        .prepareCall("/* 在此处放置你的 PL/SQL 调用 */");
stmt.setObject(1, dateTime);
stmt.execute();

总结建议

  • 不要将日期存储为数据库中的 varchar2,而是使用其 datetime 或者更好的 timestamp with time zone 数据类型。
  • 不要将日期以字符串形式发送到数据库。从 JDBC 4.2 开始,使用合适的 java.time 类型。你的 JDBC 驱动程序的文档应该告诉你应该使用的正确 Java 类型。
  • 在 Java 中,始终使用 java.time,这是现代的 Java 日期和时间 API,用于处理日期和时间。

教程链接

Oracle 教程:Date Time 解释了如何使用 java.time。

英文:

> … Suggest the best possible approach for this

This is exactly what I am doing. 如何将一系列字符转换为日期格式以存储在数据库中?

java.time and JDBC 4.2

13-sep-2020 20:48:39 is a nice date and time of day. I suppose that you meant it to indicate a point in time. It only makes sense as such within a time zone. So to store a point in time store the time with a time zone (such as Asia/Ust-Nera) or an offset from UTC (such as +10:00). Since you are using an Oracle database: If I have been correctly informed, the timestamp with time zone datatype of Oracle (contrary to other RDBMSs) is what it says: a timestamp with a time zone. So you should be able to transfer a Java ZonedDateTime to it. Do that.

First, to parse the string:

	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
	ZoneId zone = ZoneId.systemDefault();
	
	String dateTimeFromFileName = "20200913204839";
	
	ZonedDateTime dateTime = LocalDateTime.parse(dateTimeFromFileName, formatter)
			.atZone(zone);
	System.out.println("Parsed date-time: " + dateTime);

Output so far is in my time zone:

> Parsed date-time: 2020-09-13T20:48:39+02:00[Europe/Copenhagen]

I have used the default time zone of my JVM. If you can, specify a time zone in the region/city format, for example:

	ZoneId zone = ZoneId.of("Asia/Ust-Nera");

Second, to pass to a PL/SQL block that expects timestamp with time zone (not tested since I haven’t got an Oracle database at hand):

	CallableStatement stmt = yourDatabaseConnection
			.prepareCall("/* Your PL/SQL call goes here */");
	stmt.setObject(1, dateTime);
	stmt.execute();

To sum up the recommendations

  • Don’t store nor handle your date as varchar2 in the database but use its datetime or even better timestamp with time zone datatype.
  • Don’t send the date as a string to the database. Since JDBC 4.2, send an appropriate type from java.time. The documentation of your JDBC driver should tell you the correct Java type to use.
  • In Java always use java.time, the modern Java date and time API, for you date and time work.

Oracle tutorial: Date Time explaining how to use java.time.

huangapple
  • 本文由 发表于 2020年9月16日 07:59:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63911330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定