定义日期格式java'rd''st''th''nd'

时间:2015-10-28 11:35:04

标签: java date-format

我有一个字符串“星期六,10月25日,11:40”

这个日期的格式是什么?如何解析ordinal indicator

以下是我想要转换它的方式

private String changeDateFormat(String stringDate){

        DateFormat dateFormat = new SimpleDateFormat("DD, MM, ddth, hh:mm");
        try {
            Date date = dateFormat.parse(stringDate);
            dateFormat = new SimpleDateFormat("ddMMMyyyy");
            stringDate=dateFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return stringDate.toUpperCase();
    }

4 个答案:

答案 0 :(得分:1)

java doc有很多关于如何以不同格式从String解析日期的信息:

SimpleDateFormat Java Doc

您可以尝试使用此功能,但请参阅此文档并参考java doc,直到您能够解决问题为止:

DateFormat dateFormat = new SimpleDateFormat("E, MMM, dd'th' HH:mm");
Date date = dateFormat.parse("Saturday, Oct, 25th, 11:40");

尝试不同的组合,这样您就可以了解有关SimpleDateFormat的更多信息以及它如何使用不同的格式。

答案 1 :(得分:1)

希望这个程序解决你的问题。

public class Test
{
  public static void main(String[] args)  {
    System.out.println(new Test().getCurrentDateInSpecificFormat(Calendar.getInstance()));
  }

  private String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
    String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
    DateFormat dateFormat = new SimpleDateFormat("E, MMM, dd'"+ dayNumberSuffix +"', HH:mm");
    return dateFormat.format(currentCalDate.getTime());
  }

  private 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";
    }
  }

}

答案 2 :(得分:1)

SimpleDateFormat似乎不能轻易处理后面跟着“st”“th”等的日期数字。一个简单的解决方案是删除原始字符串的那一部分。 E.g。

int comma = original.lastIndexOf(',');
String stringDate =
        original.substring(0, comma - 2) +
        original.substring(comma + 1);

之后只需在stringDate上使用此格式:

SimpleDateFormat("EE, MM, dd, hh:mm")

答案 3 :(得分:1)

一种解决方案是解析参数以了解要使用的模式:

private String changeDateFormat(String stringDate) {
    DateFormat dateFormat;
    if (stringDate.matches("^([a-zA-Z]+, ){2}[0-9]+st, [0-9]{2}:[0-9]+{2}")) {
        dateFormat = new SimpleDateFormat("E, MMM, dd'st', HH:mm");
    } else if (stringDate.matches("^([a-zA-Z]+, ){2}[0-9]+nd, [0-9]{2}:[0-9]+{2}")) {
        dateFormat = new SimpleDateFormat("E, MMM, dd'nd', HH:mm");
    } else if (stringDate.matches("^([a-zA-Z]+, ){2}[0-9]+rd, [0-9]{2}:[0-9]+{2}")) {
        dateFormat = new SimpleDateFormat("E, MMM, dd'rd', HH:mm");
    } else {
        dateFormat = new SimpleDateFormat("E, MMM, dd'th', HH:mm");
    }
    try {
        Date date = dateFormat.parse(stringDate);
        dateFormat = new SimpleDateFormat("ddMMMyyyy");
        stringDate = dateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return stringDate.toUpperCase();
}

这可能需要一些优化,但它提供了这个想法。

相关问题