【发布时间】:2014-03-07 12:35:49
【问题描述】:
如何将日期格式转换为
2013-01-10 09:49:19
到
1 月 10 日
这两个值都是字符串类型。
【问题讨论】:
-
我无法想象您是如何不找到如何使用 Google 用 Java 解析和格式化日期的。
标签: java type-conversion
如何将日期格式转换为
2013-01-10 09:49:19
到
1 月 10 日
这两个值都是字符串类型。
【问题讨论】:
标签: java type-conversion
我添加了代码来计算出正确的后缀,因为这不是标准 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);
}
【讨论】:
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
【讨论】:
使用 DateFormat 类
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);
System.out.println(df.parse(myDateInString));
我认为您应该将 try catch 中的语句括起来以查找可能的异常。
【讨论】: