Java日期工具类,Java时间工具类,Java时间格式化
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年2月4日 15:03:27 星期六
http://www.cnblogs.com/fanshuyao/
附件下载见:http://fanshuyao.iteye.com/blog/2355386。
- public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
- public static final String DATE_PATTERN = "yyyy-MM-dd";
- /**
- * 日期相加减天数
- * @param date 如果为Null,则为当前时间
- * @param days 加减天数
- * @param includeTime 是否包括时分秒,true表示包含
- * @return
- * @throws ParseException
- */
- public static Date dateAdd(Date date, int days, boolean includeTime) throws ParseException{
- if(date == null){
- date = new Date();
- }
- if(!includeTime){
- SimpleDateFormat sdf = new SimpleDateFormat(StrUtils.DATE_PATTERN);
- date = sdf.parse(sdf.format(date));
- }
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- cal.add(Calendar.DATE, days);
- return cal.getTime();
- }
- /**
- * 时间格式化成字符串
- * @param date Date
- * @param pattern 如果为空,则为yyyy-MM-dd
- * @return
- * @throws ParseException
- */
- public static String dateFormat(Date date, String pattern) throws ParseException{
- if(StrUtils.isBlank(pattern)){
- pattern = StrUtils.DATE_PATTERN;
- }
- SimpleDateFormat sdf = new SimpleDateFormat(pattern);
- return sdf.format(date);
- }
- /**
- * 字符串解析成时间对象
- * @param dateTimeString String
- * @param pattern 如果为空,则为yyyy-MM-dd
- * @return
- * @throws ParseException
- */
- public static Date dateParse(String dateTimeString, String pattern) throws ParseException{
- if(StrUtils.isBlank(pattern)){
- pattern = StrUtils.DATE_PATTERN;
- }
- SimpleDateFormat sdf = new SimpleDateFormat(pattern);
- return sdf.parse(dateTimeString);
- }
- /**
- * 将日期时间格式成只有日期的字符串
- * @param dateTime Date
- * @return
- * @throws ParseException
- */
- public static String dateTimeToDateString(Date dateTime) throws ParseException{
- String dateTimeString = StrUtils.dateFormat(dateTime, StrUtils.DATE_TIME_PATTERN);
- return dateTimeString.substring(0, 10);
- }
- /**
- * 当时、分、秒为00:00:00时,将日期时间格式成只有日期的字符串,
- * 当时、分、秒不为00:00:00时,直接返回
- * @param dateTime Date
- * @return
- * @throws ParseException
- */
- public static String dateTimeToDateStringIfTimeEndZero(Date dateTime) throws ParseException{
- String dateTimeString = StrUtils.dateFormat(dateTime, StrUtils.DATE_TIME_PATTERN);
- if(dateTimeString.endsWith("00:00:00")){
- return dateTimeString.substring(0, 10);
- }else{
- return dateTimeString;
- }
- }
- /**
- * 将日期时间格式成日期对象,和dateParse互用
- * @param dateTime Date
- * @return Date
- * @throws ParseException
- */
- public static Date dateTimeToDate(Date dateTime) throws ParseException{
- Calendar cal = Calendar.getInstance();
- cal.setTime(dateTime);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- return cal.getTime();
- }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年2月4日 15:03:27 星期六
http://www.cnblogs.com/fanshuyao/