【发布时间】:2020-05-08 09:30:21
【问题描述】:
我正在尝试将当前时间戳转换为 "dd-MMM-yy HH:mm:ss a" 格式,但没有得到预期的输出。
我在 java.sql.Timestamp 中的预期输出 = 08-May-20 14:50:43 PM 我想将它存储在 Java.sql.Timestamp 变量中,但以不同的格式获得输出
注意 - 我尝试了关于 SO 的所有解决方案。我请求您提出我的代码中的问题所在。
我正在尝试将 String 转换为 java.sql.Timestamp,如上所述格式。
public class TimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Before : " + now);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yy HH:mm:ss a");
String formatDateTime = now.format(formatter);
System.out.println("formated --- " + formatDateTime);
LocalDateTime localDateTime = LocalDateTime.parse(formatDateTime, formatter);
System.out.println("DD : " + localDateTime);
Timestamp timeStamp = Timestamp.valueOf(localDateTime);
System.out.println("timeStamp : " + timeStamp);
}
}
>**My Expected output in java.sql.Timestamp = 08-May-20 14:50:43 PM**
> output - Before : 2020-05-08T14:50:43.053
> formated --- 08-May-20 14:50:43 PM
> DD : 2020-05-08T14:50:43
> timeStamp : 2020-05-08 14:50:43.0
【问题讨论】:
-
我没有
formated行的唯一日期,我还有时间和下午,你确定你的输出吗?奇怪的是你的输出,小时在下一行,为什么会这样?最后:你的代码很适合我repl.it/repls/KnowledgeableVapidCron -
@azro 有人编辑了我的问题并删除了我的实际输出。然后我重新编辑请检查一次
-
不是您奇怪的回车问题的答案,但是从输入 LocalDateTime 派生的毫秒创建 java.sql.Timestamp 不是更容易吗?
-
您已将其存储,但只是 Timestamp 的默认格式与您想要的格式不同,如果您想以您的格式显示,请格式化为字符串,以获得 ONE 表示
-
如果您的实际要求是将 LocalDateTime 转换为 java.sql.Timestamp,我仍然不确定您为什么要使用格式化字符串 - 我误解了您的最终目标吗?