如何在 Java 中将“”MMM dd, yyyy HH:mm a”转换为“yyyy-mm-dd hh:mm:ss”?

问题描述 投票:0回答:2

目标:

输入值:“

Feb 26, 2022 1:56 PM

获取上述输入值的等效日期时间值,格式为

"yyyy-mm-dd hh:mm:ss"

预期结果:

2022-02-26 13:56:00

我试过的代码:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

class convertDateTime{
    public static void main(String[] args) throws Exception{

  SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm a");
  Date date;
  date = inputFormat.parse("Feb 26, 2022 1:56 PM");
  SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  System.out.println(outputFormat.format(date));
    }
}

运行上述程序时得到的输出(不正确):

2022-02-26 01:56:00

我错过了什么?

java date datetime simpledateformat date-format
2个回答
2
投票

你使用了错误的格式。在 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html 上查看详细信息。以下是运行代码。

public static void main(String[] args) throws Exception {
    SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
    Date date = inputFormat.parse("Feb 26, 2022 1:56 PM");
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println(outputFormat.format(date));
}

输出

2022-02-26 13:56:00


1
投票

您的第一个格式需要使用

hh
而不是
HH
,因为这被定义为“上午/下午的小时”(参见 JavaDoc)。

    public static void main(String[] args) throws Exception{
        SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
        Date date;
        date = inputFormat.parse("Feb 26, 2022 1:56 PM");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(outputFormat.format(date));
    }
© www.soinside.com 2019 - 2024. All rights reserved.