【问题标题】:Change a String date into another String date将字符串日期更改为另一个字符串日期
【发布时间】:2023-04-05 22:56:01
【问题描述】:

我有一个像这样的String2013-04-19,我想将其更改为:April 19th 2013。我知道Java中有一些类,比如SimpleDateFormat,但我不知道应该使用什么样的函数。也许我需要选择班级Pattern?我需要一些帮助。

【问题讨论】:

  • 您可以从这里开始阅读:docs.oracle.com/javase/6/docs/api/java/text/…
  • 快速查看 SimpleDateFormat 的任何示例,您需要先将 parseformat 字符串转换为日期并返回字符串
  • 另外,您必须编写一个自定义方式来表示19th,因为它在SimpleDateFormat 中不是标准的。
  • 还有;在处理日期时一如既往 - 考虑使用 (JodaTime)[joda-time.sourceforge.net/]

标签: java string date


【解决方案1】:

试试下面的方法,它应该会在几天内为您提供正确的“th”、“st”、“rd”和“nd”。

public static String getDayOfMonthSuffix(final int n) {
        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";
        }
    }

public static void main(String[] args) throws ParseException {
        Date d = new SimpleDateFormat("yyyy-MM-dd").parse("2013-04-19");

        int day = Integer.parseInt(new java.text.SimpleDateFormat("dd").format(d));
        SimpleDateFormat sdf = new SimpleDateFormat("MMMMM dd'" + getDayOfMonthSuffix(day) + "' yyyy");
        String s = sdf.format(d);

        System.out.println(s);
    }

将打印April 19th 2013

(日终止改编自this post

【讨论】:

  • 谢谢,我会尽快尝试。
  • 它还会显示“13rd”和“12nd”
【解决方案2】:

试试这个:

String originalDate = "2013-04-19";
Date date = null;
try {
    date = new SimpleDateFormat("yyyy-MM-dd").parse(originalDate);
} catch (Exception e) {
}
String formattedDate = new SimpleDateFormat("MMMM dd yyyy").format(date);

不会打印st、nd、rd等

【讨论】:

    【解决方案3】:

    仅使用 SimpleDateFormat 类中的 parse 方法 试试这个:

    new SimpleDateFormat("MMM dd YYYY").parse("2013-04-19");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 2016-04-11
      相关资源
      最近更新 更多