论坛首页 入门技术论坛

一些关于日期操作的方法(二)

浏览 1375 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-06-10  

   日期格式字符串生成Date:

  

private static final String SHORT_FORMAT = "yyyy-MM-dd";
private static final String LONG_FORMAT = "yyyy-MM-dd HH:mm:ss";

public static Date getFormatDate(String dateString, String formatType) {
		Date ret = null;
		try {
			if (dateString == null || dateString.equals("") || formatType == null
					|| formatType.equals("")) {
				return new Date();
			}
			ret = new SimpleDateFormat(formatType).parse(dateString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

 

2.获取日期所在周的星期一和星期日的日期

 

 

public static Date getWeekStartDate(Date date) {
		Date ret = null;
		try {
			if (date == null) {
				return ret;
			}

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);

			int weekDay = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			switch (weekDay) {
			case 0:
				calendar.add(Calendar.DAY_OF_MONTH, -6);
				break;
			case 1:
				break;
			default:
				calendar.add(Calendar.DAY_OF_MONTH, -(weekDay - 1));
			}

			ret = calendar.getTime();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static Date getWeekEndDate(Date date) {
		Date ret = null;
		try {
			if (date == null) {
				return ret;
			}

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);

			int weekDay = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			switch (weekDay) {
			case 0:
				break;
			default:
				calendar.add(Calendar.DAY_OF_MONTH, (7 - weekDay));
			}

			ret = calendar.getTime();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics