Java 将日期从一种格式转换为另一种格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22250281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:32:51  来源:igfitidea点击:

Java convert date from one format to another

javatype-conversion

提问by subash

How can I convert date form to

如何将日期格式转换为

2013-01-10 09:49:19

2013-01-10 09:49:19

to

10th Jan.

1 月 10 日

both values are of string types.

两个值都是字符串类型。

采纳答案by david99world

I added the code to work out the correct suffix as this isn't part of the standard JDK. To be fair that's probably the only bit of this question that isn't just a SimpleDateFormat#format()call.

我添加了代码来计算正确的后缀,因为这不是标准 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);
}

回答by Harmlezz

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);

Output is:

输出是:

10th Jan

回答by MjZac

Use the DateFormat class

使用 DateFormat 类

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

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

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

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

I think you should surround the statements in try catch for possible exceptions.

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