【问题标题】:Convert date to friendly format using SimpleDateFormat使用 SimpleDateFormat 将日期转换为友好格式
【发布时间】:2014-06-30 04:59:24
【问题描述】:

我正在尝试将日期(例如 Mon Jul 28 00:00:00 CDT 2014)格式化为对用户更友好的内容,例如 Mon 6/28。我做错了什么?

代码:

        String date_string = "Mon Jul 28 00:00:00 CDT 2014";

        SimpleDateFormat inputFormatter = new SimpleDateFormat("ccc LLL F HH:mm:ss zzz yyyy"); //please notice the    capital M
        SimpleDateFormat outputFormatter = new SimpleDateFormat("ccc LLL/yyyy");

        try {
            Date date = inputFormatter.parse(date_string);
            String text = outputFormatter.format(date);
            System.out.println(text);
        } catch (ParseException e) {
            e.printStackTrace();
        }

当我使用 System.out.println 查看 outputFormatter 设置为什么时,结果是:Sun Jan/2015

【问题讨论】:

标签: java android date time simpledateformat


【解决方案1】:

试试这个..

改变这个..

    SimpleDateFormat outputFormatter = new SimpleDateFormat("ccc LLL/yyyy");

到

    SimpleDateFormat outputFormatter = new SimpleDateFormat("EEE M/dd");

EEE --> 星期一

EEEE --> 星期一

MM --> 06

M --> 6

dd --> 28

编辑

    SimpleDateFormat inputFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

演示

http://ideone.com/c5rVT5

【讨论】:

  • 谢谢,这确实将输出格式更改为我想要的格式,但是,它仍然显示不正确的信息。输出为 Sun 1/11。
  • 应该是 6 月 28 日星期一。
  • 谢谢!!它工作得很好:D 希望我不会被否决,但除此之外,我很高兴。
【解决方案2】:

“月份:如果模式字母的个数为3个或更多,则将月份解释为文本;否则,将其解释为数字。”

如果您想要数字版本,请在输出中使用较短的格式。

【讨论】:

    【解决方案3】:

    试试这个

    DateFormat df = new SimpleDateFormat("EEE M/dd");
    

    查看this 和this 了解更多详情。

    【讨论】:

    • 你应该为你的答案添加一些解释
    【解决方案4】:
    SimpleDateFormat inputFormatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
    SimpleDateFormat outputFormatter = new SimpleDateFormat("EEE MMM/yyyy");
    

    这将打印:Mon Jul/2014

    如果你使用:

    SimpleDateFormat outputFormatter = new SimpleDateFormat("EEE L/d");
    

    这将打印:Mon 7/28

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多