【问题标题】:Change a Java date-time string to date将 Java 日期时间字符串更改为日期
【发布时间】:2018-01-17 10:15:16
【问题描述】:

嗯,我试图寻找很多问题,但找不到相关的东西。我有一个包含以下数据的字符串:

String sDate = "2018-01-17 00:00:00";

这来自一个应用程序,我需要将其转换为以下日期格式

17-01-2018

我经历了这个link,但无法联系。

有人可以帮忙吗..?

【问题讨论】:

标签: java date datetime datetime-format date-formatting


【解决方案1】:

如果您使用的是 Java 8,则可以使用 java.time 库和:

String sDate = "2018-01-17 00:00:00";

//Step one : convert the String to LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(sDate, formatter);

//Step two : format the result date to dd-MM-yyyy
String result = date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));

输出

17-01-2018

另一个过度工程解决方案(它只适用于您的情况)您可以从LocalDateTime 的默认格式中受益:

String result = LocalDateTime.parse(sDate.replace(" ", "T"))
        .format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));

【讨论】:

  • 这是一个很好的现代解决方案。如果您还没有使用 Java 8 或 9,您仍然可以在将 ThreeTen Backport 添加到您的项目时使用相同的方式。
【解决方案2】:
public static void main(String args[]) {  
String sDate = "2018-01-17 00:00:00";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = df.parse(sDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
        System.out.println(df1.format(date));

}


it should solve your problem.

【讨论】:

【解决方案3】:

您需要使用 SimpleDateFormat:

    String sDate = "2018-01-17 00:00:00";
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = df.parse(sDate);

    SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
    System.out.println(df1.format(date));

查看SimpleDateFormat 课程以了解详细信息

【讨论】:

  • 使用HH 而不是hh
  • 像魅力一样工作!也感谢您的链接
  • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。今天我们在java.time, the modern Java date and time API 的表现要好得多。
猜你喜欢
  • 1970-01-01
  • 2017-04-08
  • 2023-04-05
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多