您的位置 首页 java

整理 | Java日期工具类

我们首先对日期格式化设定默认的规则:

 //默认的日期格式化规则 
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd"; 
//默认的日期时间格式化规则 
private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
 

根据给定的日期时间规则转换成 字符串

什么时候需要将日期转换为字符串呢?比如我们查询单个新闻,在返回给前端数据的时候,我们需要对发布时间进行格式化,我们只需要它的日期时间,并不需要知道它的具体发布时间是几秒钟,因此,我们需要对日期进行格式化,将其格式化为“yyyy-MM-dd HH:mm”。而在工具类中,我们需要提供一个转换方法。

 /** 
 * 根据给定的日期时间规则转换成字符串 
 * @param date 需要转换的日期 
 * @param pattern 以该规则转成字符串 
 * @return 
 */ 
public static String dateToStr(Date date, String pattern) { 
 //若规则为空,则以默认的规则显示 
 if(pattern.isEmpty()) { 
 pattern = DEFAULT_DATE_PATTERN;
 } 
 SimpleDateFormat sdf = new SimpleDateFormat(pattern); 
 return sdf.format(date); 
}
 

将给定的日期字符串解析成日期对象

我们需要查询指定日期的数据时,前端给出的查询日期为字符串格式,这时我们需要将其解析成日期对象,这样才能在数据库中获取到数据。

 /**
 * 将指定字符串解析成时间对象
 * @param dateStr 时间字符串
 * @param pattern 解析规则
 * @return
 * @throws ParseException
 */ public static Date strToDate(String dateStr, String pattern) throws ParseException {
 if(pattern.isEmpty()) {
 pattern = DEFAULT_DATE_PATTERN;
 }
 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
 return sdf.parse(dateStr);
 }
 

获取指定时间的前后时间

目前大多数的数据分析都会以今天、昨天、七天、十五天等为基准来进行分析,而获取当前时间的前一天或前几天数据需要对日期时间进行处理。

 /**
 * 获取指定时间的前后时间
 * @param date 指定时间
 * @param num 负数为指定时间之前几天,正数为指定时间之后几天
 * @return
 */ public static Date beforeOrAfterOfDate(Date date, int num) {
 Calendar calendar = Calendar. getInstance ();
 calendar.setTime(date);
 calendar.add(Calendar.DAY_OF_MONTH, num);
 return calendar.getTime();
 }
 

获取指定日期月份开始时间和月份结束时间

我们需要当前月份的数据时,需要查询从月份开始时间到月份结束时间。比如查询上月的发文数量、新注册用户等等。

 /**
 * 获取指定日期所在月份的开始日期
 * @param date
 * @return
 */ public static Date getBeginDateOfMonth(Date date) {
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(date); //设置本月第一天,1号 
 calendar.set(Calendar.DAY_OF_MONTH, 1); //设置小时,0 
 calendar.set(Calendar.HOUR_OF_DAY, 0); //设置分钟,0 
 calendar.set(Calendar. MINUTE , 0); //设置秒,0 
 calendar.set(Calendar. SECOND , 0); //设置毫秒,0 
 calendar.set(Calendar.MILLISECOND, 0);
 return calendar.getTime();
 }
 /**
 * 获取指定日期所在月份的结束日期
 * @param date
 * @return
 */ public static Date getEndDateOfMonth(Date date) {
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(date); //设置本月最后一天 
 calendar.set(Calendar.DAY_OF_MONTH, 
 calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); //设置小时,23 
 calendar.set(Calendar.HOUR_OF_DAY, 23); //设置分钟,59 
 calendar.set(Calendar.MINUTE, 59); //设置秒,59 
 calendar.set(Calendar.SECOND, 59); //设置毫秒,999 
 calendar.set(Calendar.MILLISECOND, 999);
 return calendar.getTime();
 }
 

文章来源:智云一二三科技

文章标题:整理 | Java日期工具类

文章地址:https://www.zhihuclub.com/180281.shtml

关于作者: 智云科技

热门文章

网站地图