首页 > 解决方案 > 在没有格式化程序的情况下将时间戳转换为字符串

问题描述

我从 Oracle DB 中得到一个 TIMESTAMP,格式如下:yyyy-MM-dd hh:mm:ss.SSS并希望转换为类似dd.MM.yyyy的字符串。我执行了字符串操作,结果按预期正确。这种方法是还是?还是用作格式化程序更有效?如果 Oracle 由于 NLS_LANG 设置不同而在将来返回不同的字符串,我是否必须使用格式化程序?

String date = data.toString().substring(0,10).replace("-","."); // data is received from DB 
String day = datum.substring(8,10); 
String month = datum.substring(4,8); 
String year = datum.substring(0,4); 
String myDate = new StringBuilder().append(day).append(month).append(year).toString();

标签: javastringoracletimestampformatter

解决方案


java.time

ANSI SQL 类型与类型的映射在Oracle 的文章java.time中描述如下:

ANSI SQL Java SE 8
日期 本地日期
时间 当地时间
时间戳 本地日期时间
时区时间 偏移时间
带有时区的时间戳 偏移日期时间

LocalDateTime下面给出了从检索 a 的示例代码columnfoo

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE <some condition>");
while (rs.next()) {
    // Assuming the column index of columnfoo is 1
    LocalDateTime ldt = rs.getObject(1, LocalDateTime.class));
    System.out.println(ldt);
}
rs.close();
st.close();

如何格式化一个LocalDateTime

您可以使用DateTimeFormatter来格式化LocalDateTime.

演示:

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

public class Main {
    public static void main(String[] args) {
        // This is a dummy LocalDateTime for the purpose of demo. You will retrieve
        // LocalDateTime from the DB as shown above
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.uuuu", Locale.ENGLISH);
        String formatted = ldt.format(dtf);
        System.out.println(formatted);
    }
}

输出:

29.10.2021

ONLINE DEMO

Trail: Date Time了解有关现代日期时间 API *的更多信息。


* 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请通过 desugaring 检查可用的 Java 8+ API。请注意,Android 8.0 Oreo 已经提供java.time.


推荐阅读