我如何从日历中获取“字符串”日期?
How can i get `String` date from calendar?
如何从日历中获取 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 sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(calendardate.getTime());
您应该使用 SimpleDateFormat
class,如下所示。
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());
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 returns 所需格式的日期。
您可以使用 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
如何从日历中获取 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 sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(calendardate.getTime());
您应该使用 SimpleDateFormat
class,如下所示。
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());
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 returns 所需格式的日期。
您可以使用 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