我如何解析“Thu,8 Dece 2016 09:54:00 GMT”与本月额外的'e'?

时间:2016-12-08 18:48:04

标签: java simpledateformat

我可以解析所有类型的日期,但这个日期有一个额外的字母。我该如何解析这个?

我不知道剩下的几个月会怎样,但希望他们以4个字母的形式出现。我使用格式E, dd MMM yyyy HH:mm:ss z,异常出现在偏移量10。

2 个答案:

答案 0 :(得分:2)

您可以自定义SimpleDateFormat使用的DateFormatSymbols

DateFormatSymbols symbols = DateFormatSymbols.getInstance();

String[] months = symbols.getShortMonths();
months[11] = "Dece";
symbols.setShortMonths(months);

DateFormat fmt =
    new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", symbols);

String s = "Thu, 8 Dece 2016 09:54:00 GMT";
Date date = fmt.parse(s);

您也可以使用Java 8日期时间类来完成它,虽然它有点冗长:

Locale locale = Locale.getDefault();
Map<Long, String> monthNames = new HashMap<>(12);
for (Month month : Month.values()) {
    long value = month.getValue();
    String name = month.getDisplayName(TextStyle.SHORT, locale);
    monthNames.put(value, name);
}

monthNames.put(12L, "Dece");

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.appendPattern("EEE, d ");
builder.appendText(ChronoField.MONTH_OF_YEAR, monthNames);
builder.appendPattern(" yyyy HH:mm:ss z");

DateTimeFormatter formatter = builder.toFormatter();

String s = "Thu, 8 Dece 2016 09:54:00 GMT";
ZonedDateTime dateTime = ZonedDateTime.parse(s, formatter);
Date date = Date.from(dateTime.toInstant());

答案 1 :(得分:0)

CategoryImageIL.Images.Clear();
        MainTabs.TabPages.Clear();
        if (categories != null && categories.Count != 0)
        {

            int counter = 0;

            foreach (var cat in categories)
            {
                Image catImage = byteArrayToImage(cat.Attachment.Value);
                CategoryImageIL.Images.Add("Image" + cat.Attachment.AttachmentId.ToString(), catImage);

                TabPage tab = new TabPage();
                tab.BackColor = Color.Gainsboro;
                tab.BackgroundImage = null;
                tab.Size = new Size(888, 456);
                tab.Name = "Cat" + cat.CategoryId.ToString();
                tab.ImageIndex = counter;
                MainTabs.TabPages.Add(tab);
                counter++;
            }
        }
        MainTabs.SelectedIndex = 0;
        MainTabs.Refresh();

如果您使用的格式为// java String input = "Thu, 8 Dece 2016 09:54:00 GMT"; String p = "[^.*,\\s\\d+\\s+]+[\\s+]"; Pattern pattern = Pattern.compile(p); Matcher m = pattern.matcher(input); while (m.find()) { String month = m.group().substring(0, 3); input = input.replaceFirst(p, month + " "); } System.out.println(input); // Thu, 8 Dec 2016 09:54:00 GMT ,则日期字符串应如E, dd MMM yyyy HH:mm:ss Z。不知道为什么这个月有4个字符。在前面的例子中,您可以使用Thu, 08 Dec 2016 19:33:26 +0000

从一种格式转换为另一种格式
SimpleDateFormat