【问题标题】:How to format date string in java? [duplicate]如何在java中格式化日期字符串? [复制]
【发布时间】:2012-06-18 06:01:18
【问题描述】:

嗨,我有以下字符串:2012-05-20T09:00:00.000Z 我想将其格式化为 20/05/2012, 9am

如何在java中做到这一点?

谢谢

【问题讨论】:

  • 现代答案:使用 java.time,现代 Java 日期和时间 API。 OffsetDateTime.parse("2012-05-20T09:00:00.000Z").format(DateTimeFormatter.ofPattern("dd/MM/uuuu"))。或者更好的是,使用DateTimeFormatter.ofLocalizedDate()

标签: java date datetime simpledateformat


【解决方案1】:

如果您正在为您的特定情况寻找解决方案,它会是:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);

【讨论】:

  • Date 必须是 java.util.Date,用 java.sql.Date 是不行的(只是一个注释)
【解决方案2】:
package newpckg;

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

public class StrangeDate {

    public static void main(String[] args) {

        // string containing date in one format
        // String strDate = "2012-05-20T09:00:00.000Z";
        String strDate = "2012-05-20T09:00:00.000Z";

        try {
            // create SimpleDateFormat object with source string date format
            SimpleDateFormat sdfSource = new SimpleDateFormat(
                    "yyyy-MM-dd'T'hh:mm:ss'.000Z'");

            // parse the string into Date object
            Date date = sdfSource.parse(strDate);

            // create SimpleDateFormat object with desired date format
            SimpleDateFormat sdfDestination = new SimpleDateFormat(
                    "dd/MM/yyyy, ha");

            // parse the date into another format
            strDate = sdfDestination.format(date);

            System.out
                    .println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
            System.out.println("Converted date is : " + strDate.toLowerCase());

        } catch (ParseException pe) {
            System.out.println("Parse Exception : " + pe);
        }
    }
}

【讨论】:

    【解决方案3】:

    首先使用SimpleDateFormatparse() StringDate 然后format() DateString

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2012-01-07
      相关资源
      最近更新 更多