java - 如何在java中将当前时间戳转换为特定的时间戳格式
问题描述
我正在尝试将当前时间戳转换为“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
解决方案
我认为您可以使用DateTimeFormatter
:
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Main
{
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yy HH:mm:ss a");
LocalDateTime dt = LocalDateTime.now();
System.out.println(dtf.format(dt));
}
}
推荐阅读
- google-cloud-platform - 检查 Google Cloud API 和服务错误日志
- python - 什么 Cygwin 包允许我调试 Python 代码?
- javascript - 在没有ajax的情况下获取并发送一个Json文件(拖放)到服务器
- c++ - 使用 ReadTheOrg 将文字程序导出为 HTML 时保留源代码块的内容
- jquery - ajax调用后如何从MVC模型重新加载数据表
- r - /usr/bin/shiny-server.sh:在 Ubuntu 上运行 R 闪亮的 docker 时权限被拒绝
- mysql - MariaDB 配置更改不生效
- php - 将带引号的参数传递给准备好的语句 PDO
- javascript - React 中的子域路由
- reactjs - 如何使用反应挂钩删除查询参数?