[英]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
這是可能的? 怎么樣?
您可以使用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
您應該使用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());
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以您所需的格式返回日期。
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(calendardate.getTime());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.