【问题标题】:How can i get `String` date from calendar?如何从日历中获取“字符串”日期?
【发布时间】:2015-05-13 06:17:18
【问题描述】:

如何从日历中获取String 日期?

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MOUNTH, -5); //set now and 5 days to back

我想像这样得到String(日期间隔-5天到今天):

11.03.2015
10.03.2015
.
.
.
07.03.2015

有可能吗?怎么样?

【问题讨论】:

  • 看看 SimpleDateFormat 类。
  • 我想得到所有的日期,而不仅仅是一个。
  • 为什么说它是重复的,然而,完全是另外一回事
  • 我想在 -5 天到今天的间隔内获取字符串日期

标签: java string calendar


【解决方案1】:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(calendardate.getTime());

【讨论】:

  • 我想在 -5 天到今天的间隔内获取字符串日期
  • 请在您的答案中添加解释。
  • 感谢您提供此代码 sn-p,它可能会提供一些即时帮助。正确的解释将greatly improve 其教育价值通过说明为什么这是解决问题的好方法,并使其对未来有类似但不相同的问题的读者更有用。请编辑您的答案以添加解释,并说明适用的限制和假设。
【解决方案2】:

您可以使用 for 循环并从日历实例中减少一天并打印出来

Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");

for (int index = 1; index <= 5; index++) {
    calendar.add(Calendar.DATE, -1);
    System.out.println(dateFormat.format(calendar.getTime()));
}

输出:

10.03.2015
09.03.2015
08.03.2015
07.03.2015
06.03.2015

【讨论】:

    【解决方案3】:
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    Long beforeTime = date - (5*24*60*60*1000);
    Date beforeDate = new Date(beforeTime);
    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    String s = format.format(beforeDate);
    

    s 以您所需的格式返回日期。

    【讨论】:

    • 我想在 -5 天到今天的间隔内获取字符串日期
    • 你可以使用下面的逻辑代替上面代码sn-p中的日期。 (我在上面的sn-p中修改过)Long beforeTime = (date.getTime())-(5*24*60*60*1000);日期 beforeDate = new Date(beforeTime);
    【解决方案4】:

    您应该使用SimpleDateFormat 类,如下所示。

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MOUNTH -5);
    SimpleDateFormat myDateFormat = new SimpleDateFormat("MM.dd.yyyy"); //or ("dd.MM.yyyy"), If you want days before months.
    String formattedDate = myDateFormat.format(cal.getTime());
    

    【讨论】:

    • 它只有一个,它可能在非时间和-5之间获取日期?
    • 对不起@chefrisl,我现在才明白你的问题。 Prasad Khode 的答案就是你要找的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 2019-05-05
    相关资源
    最近更新 更多