java中的DateAdd

         /**
	 * 追溯到 startDate的前 Interval天
	 * @param startDate
	 * @param Interval
	 * @return
	 * @throws ParseException 
	 */
	public static String[] getBeforeTime(String startDate, int Interval) throws ParseException {
		String[] beforeTime = new String[Interval+1];
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if ("".equals(startDate) || startDate == null) {// 如果選擇的時間為空,則從當前時間開始
		} else {
			try {
				calendar.setTime(sdf.parse(startDate));// 否則從選擇的時間開始
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
//		System.out.println("開始時間:"+sdf.format(calendar.getTime()));
		beforeTime[0]=sdf.format(sdf.parse(startDate));
		for (int i = 1; i <= Interval; i++) {
			calendar.add(calendar.DAY_OF_MONTH, -1);
			beforeTime[i] = sdf.format(calendar.getTime());
		}

//		for (String j : beforeTime) {
//			System.out.println(j);
//		}
//		System.out.println("結束時間"+sdf.format(calendar.getTime()));
		
//		calendar.setTime(new Date());
//		System.out.println("當前時間"+sdf.format(calendar.getTime()));
		return beforeTime;
	}

   主要通過

Calendar 類相關API實現

你可能感兴趣的:(java,J#)