【问题标题】:Java convert date from one format to anotherJava将日期从一种格式转换为另一种格式
【发布时间】:2014-03-07 12:35:49
【问题描述】:

如何将日期格式转换为

2013-01-10 09:49:19

1 月 10 日

这两个值都是字符串类型。

【问题讨论】:

标签: java type-conversion


【解决方案1】:

我添加了代码来计算出正确的后缀,因为这不是标准 JDK 的一部分。公平地说,这可能是这个问题中唯一不仅仅是SimpleDateFormat#format() 电话。

static String[] suffixes =
          //    0     1     2     3     4     5     6     7     8     9
             { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
          //    10    11    12    13    14    15    16    17    18    19
               "th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
          //    20    21    22    23    24    25    26    27    28    29
               "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
          //    30    31
               "th", "st" };

public static void main(String args[]) throws ParseException {
    String string = "2013-01-10 09:49:19";
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(string);
    SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
    SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
    String dayStr =
            dayFormat.format(date)
                    + suffixes[Integer.parseInt(dayFormat.format(date))]
                    + " " + monthFormat.format(date) + ".";
    System.out.println(dayStr);
}

【讨论】:

    【解决方案2】:
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2013-01-10 09:49:19");
    String format = new SimpleDateFormat("dd'th' MMM").format(date);
    System.out.println(format);
    

    输出是:

    10th Jan
    

    【讨论】:

    • 这不太正确,好像是当月 3 日,应该是 1 月 3 日,这是不正确的。
    【解决方案3】:

    使用 DateFormat 类

    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);

    System.out.println(df.parse(myDateInString));

    我认为您应该将 try catch 中的语句括起来以查找可能的异常。

    【讨论】:

      猜你喜欢
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 2017-08-27
      相关资源
      最近更新 更多