首页 > 解决方案 > 如何在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

标签: javatimestamp

解决方案


我认为您可以使用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));  

    }
}

推荐阅读