如何从日历中获取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
有可能吗?怎么样?
答案 0 :(得分:5)
你可以使用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
答案 1 :(得分:2)
您应该使用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());
答案 2 :(得分:1)
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);
以您所需的格式返回日期。
答案 3 :(得分:0)
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(calendardate.getTime());