Java实用代码片段

Posted by dingqiang.l on March 8, 2018

获取指定日期的某一周的第一天和最后一天

/**
 * 获取指定日期的某一周的第一天和最后一天
 * 
 * @param date
 *            选定的日期
 * @param index
 *            表示那一周,例:0表示当前周,-1表示上一周,1表示下一周
 * @return
 * @throws Exception
 *             可能出现的时间格式转换异常
 */
public static String getWeekFirstAnfLastDate(String date, int index) throws Exception {
	Calendar calendar = Calendar.getInstance()
	calendar.setTime(new SimpleDateFormat("yyyyMMdd").parse(date));
	int d = 0;
	if (calendar.get(Calendar.DAY_OF_WEEK) == 1) {
		d = -6;
	} else {
		d = 2 - calendar.get(Calendar.DAY_OF_WEEK);
	}
    calendar.add(Calendar.WEEK_OF_YEAR, index);
    // 该周开始日期
    calendar.add(Calendar.DAY_OF_WEEK, d);
    String weekFirstDate = getFormatDate(calendar.getTime(),"yyyy.MM.dd");
    // 该周结束日期
    calendar.add(Calendar.DAY_OF_WEEK, 6);
    String weekLastDate = getFormatDate(calendar.getTime(),"yyyy.MM.dd");
    return weekFirstDate + " - " + weekLastDate;
} ##### 2、时间字符串格式转换
/**
 * 时间字符串转换成另一种格式,如yyyyMMddHHmmss转成yyyy-MM-dd HH:mm:ss
 * @param strDate 要转换的时间字符串:20180411104850
 * @param fromFormat 原格式
 * @param toFormat 最终格式
 * @return
 */
public static String strFormatDate(String strDate,String fromFormat,String toFormat) {
	Date date = null;
	SimpleDateFormat sdf = null;
	try {
		date = new SimpleDateFormat(fromFormat).parse(strDate);
		sdf = new SimpleDateFormat(toFormat);
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return sdf.format(date);
}