java - 在没有格式化程序的情况下将时间戳转换为字符串
问题描述
我从 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();
解决方案
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
从Trail: Date Time了解有关现代日期时间 API *的更多信息。
* 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请通过 desugaring 检查可用的 Java 8+ API。请注意,Android 8.0 Oreo 已经提供对java.time
.
推荐阅读
- torch - 加载保存的 NER 变压器模型会导致 AttributeError?
- python - Django ModelForm 表单未发布
- r - How should I upgrade R properly to keep older versions running [Windows]?
- java - 如何将 SameSite 和 Secure 属性设置为 JSESSIONID cookie
- download - 是否有从外部来源收集图像文件的快速方法(Chrome 开发人员选项卡)
- c# - pdfCrowd 现场直播失败
- r - 将 16.2Gb dist 转换为 R 中的矩阵
- pytorch - 用于在 GPU 上训练神经网络的非确定性行为,在 PyTorch 中实现并具有固定的随机种子
- python - 如何使用字符串列表计算列值的出现次数
- c# - 放置静态api密钥并将其与标头中的请求匹配是一种好方法吗?