我有dd/mm/yyyy格式的日期,但我想以5 月 2 日或 6 月 5 日之类
的方式解析它任何人请建议使用DateFormat
或SimpleDateFormat
类的东西?
编辑:我已经尝试过的一个小快照:-
Date d = Date.parse("20/6/2013");
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM");
String dateString = sdf.format(d);
我有dd/mm/yyyy格式的日期,但我想以5 月 2 日或 6 月 5 日之类
的方式解析它任何人请建议使用DateFormat
或SimpleDateFormat
类的东西?
编辑:我已经尝试过的一个小快照:-
Date d = Date.parse("20/6/2013");
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM");
String dateString = sdf.format(d);
您可以使用以下方法:-
String getDaySuffix(final int n) {
if(n < 1 || n > 31)
return "Invalid date";
if (n >= 11 && n <= 13)
return "th";
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
你需要用“”分割它。如下所示:
Staring split[] = dateString .split[" "];
String date = split[0];
String suffix = getDate(Integer.parseInt(date));
String YourDesireString = date + suffix + " " + split[1];
getDate的功能如下
String getDate(final int n) {
if(n <= 1 || n >= 31)
return "Invalid date";
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
YourDesireString 就是您想要的答案。祝你好运
我不认为它可以通过 SimpleDateFormat 完成。但这是实现相同目标的替代解决方案。
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" };
Date date = new Date();
int day = Calendar.getInstance().setTime(date).get(Calendar.DAY_OF_MONTH);
String dayStr = day + suffixes[day];
没有内置函数来获取日期格式,如 1st 或 5th ..我们必须手动将后缀添加到日期..希望下面的代码可能对您有用。
公共类 WorkWithDate {
private static String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
DateFormat dateFormat = new SimpleDateFormat(" d'" + dayNumberSuffix + "' MMMM yyyy");
return dateFormat.format(currentCalDate.getTime());
}
private static String getDayNumberSuffix(int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
public static void main(String [] args) throws ParseException {
System.out.println(getCurrentDateInSpecificFormat(Calendar.getInstance()));
}
}