如何将日期值“2017年5月26日”转换为“2017年5月26日”?

时间:2017-05-25 16:46:56

标签: java date java-8 date-format

是否有可用于解析语言特定序数指标/后缀的java库?

我的日期值如下:26th May 2017。我想将其转换为26/05/2017。有人可以指导我怎么做吗?

4 个答案:

答案 0 :(得分:3)

您可以使用自定义日期格式将此格式直接解析为Java 8 LocalDate

static final Map<Long, String> ORDINAL_DAYS = new HashMap<>();
static
 {
   ORDINAL_DAYS.put(1, "1st");
   .... more ....
   ORDINAL_DAYS.put(26, "26th");
   .... more ....
   ORDINAL_DAYS.put(31, "31st");
 }

static final DateTimeFormatter FORMAT_DAY_MONTH_YEAR = new DateTimeFormatterBuilder()
  .appendText(ChronoField.DAY_OF_MONTH, ORDINAL_DAYS)
  .appendLiteral(' ')
  .appendText(ChronoField.MONTH_OF_YEAR)
  .appendLiteral(' ')
  .appendText(ChronoField.YEAR)
  .toFormatter();


 String dateInString = "26th May 2017";

 LocalDate date = LocalDate.parse(dateInString, FORMAT_DAY_MONTH_YEAR);

这是使用DateTimeFormatter.appendText的版本,它接受用于映射日期字符串的地图。

为了简洁,您需要填写我遗漏的ORDINAL_DAYS中的所有缺失条目。

答案 1 :(得分:2)

假设您不需要非常严格的输入验证,因为您要从转换<{1}}上的格式(或thstnd31st及更多内容中,我建议您先删除这两个字母。正则表达式可能会这样做:

2nd

结果是

    // remove st, nd, rd or th after day of month
    dateInString 
            = dateInString.replaceFirst("^(\\d+)(st|nd|rd|th)( \\w+ \\d+)$", "$1$3");
    String dateOutString = LocalDate.parse(dateInString, 
                    DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH))
            .format(DateTimeFormatter.ofPattern("dd/MM/uuuu"));

如果您的输入包含月份的三个字母缩写,如4月,5月或6月,则此方法有效。要接受完整的月份名称(4月,5月,6月),格式模式中需要4个Ms而不是3个:26/05/2017

答案 2 :(得分:2)

如@ OleV.V所述。在this comment中,您可以使用带有可选部分的模式(以解析不同的后缀 st nd rd )。

您还必须使用java.util.Locale强制将月份名称改为英语。代码将是这样的:

String input = "26th May 2017";
DateTimeFormatter parser = DateTimeFormatter
    // parse the day followed by st, nd, rd or th (using optional patterns delimited by [])
    .ofPattern("dd['st']['nd']['rd']['th'] MMM yyyy")
    // force English locale to parse month names
    .withLocale(Locale.ENGLISH);
// formatter for dd/MM/yyyy output
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withLocale(Locale.ENGLISH);
System.out.println(formatter.format(parser.parse(input))); // 26/05/2017

上面的代码适用于包含3个字母的月份名称(例如 5月 8月)。如果您要解析全名(例如八月三月),只需将MMM更改为MMMM

DateTimeFormatter parser = DateTimeFormatter
    // using MMMM to parse full month name (like "August")
    .ofPattern("dd['st']['nd']['rd']['th'] MMMM yyyy")
    .withLocale(Locale.ENGLISH);

PS:如果您想使用相同的parser解析这两种情况(3个字母或完整月份名称),您可以这样做:

DateTimeFormatter parser = DateTimeFormatter
    // can parse "March" or "Mar" (MMMM or MMM)
    .ofPattern("dd['st']['nd']['rd']['th'][ MMMM][ MMM] yyyy")
    .withLocale(Locale.ENGLISH);

答案 3 :(得分:1)

假设您在询问Java,请点击此链接:https://www.mkyong.com/java/how-to-convert-string-to-date-java/可以为您提供帮助。

总体要点是:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateExample3 {

    public static void main(String[] argv) {



        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

        String dateInString = "26th May 2017"; // Remove your 'th', 'nd', etc. from the input string.

        String withoutEnding = dateInString;
        //Something like this
        if(dateInString.contains("th") withoutEnding = dateInString.replace("th", "");
        if(dateInString.contains("nd") withoutEnding = dateInString.replace("nd", "");
        if(dateInString.contains("st") withoutEnding = dateInString.replace("st", "");
        if(dateInString.contains("rd") withoutEnding = dateInString.replace("rd", "");

        try {

            Date date = formatter.parse(withoutEnding);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

dd/MM/yyyy是一个可以提供给您的日期格式化程序 26/05/2017

希望这有帮助!

编辑:另请参阅http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html以获取SimpleDateFormat的不同模式字母的完整列表。