作为一个后端码农,对于时间的处理还是比较多的,这里分享一个关于时间的工具类,简单整理了一下,测试了方法并添加相关注释。
/**
* @Description 时间的工具类
* @author linmengmeng
* @date 2019年1月19日 下午3:08:16
*/
public class DateUtil {
/**
* @Description: 返回格式化后的日期信息
* @param date
* @param format
* @return String
*/
public static String getDate(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
/**
* @Description: 返回格式化后的日期信息。默认格式为yyyy-MM-dd
* @param date
* @return String
*/
public static String getDate(Date date) {
return getDate(date, "yyyy-MM-dd");
}
/**
* @Description: 将字符串转化为日期类型
* @param date
* @param format
* @return Date
*/
public static Date parse(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* @Description: 将字串转化为日期类型,日期必须为:"yyyy-MM-dd"
* @param date
* @return Date
*/
public static Date parse(String date) {
return parse(date, "yyyy-MM-dd");
}
/**
* @Description: 将字符串时间转为Timestamp
* @param date
* @param format
* @return Timestamp
*/
public static Timestamp date2Timestamp(String date, String format) {
Date d = parse(date, format);
if (d != null) {
return new Timestamp(d.getTime());
}
return null;
}
/**
* 将一个字符串日期yyyy-MM-dd转化为Timestamp
* @param date
* @return Timestamp
*/
public static Timestamp date2Timestamp(String date) {
return date2Timestamp(date, "yyyy-MM-dd");
}
/**
* @Description: 获取本周一的日期
* @return String
*/
public static String getFirstDayOfWeek(){
Calendar currentDate = new GregorianCalendar();
currentDate.setFirstDayOfWeek(Calendar.MONDAY);
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return getDate(currentDate.getTime());
}
/**
* @Description: 获取本周日的日期
* @return String
*/
public static String getLastDayOfWeek(){
Calendar currentDate = new GregorianCalendar();
currentDate.setFirstDayOfWeek(Calendar.MONDAY);
currentDate.set(Calendar.HOUR_OF_DAY, 23);
currentDate.set(Calendar.MINUTE, 59);
currentDate.set(Calendar.SECOND, 59);
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return getDate(currentDate.getTime());
}
/**
* 计算两个日期之间相差的秒数
* @param date1
* @param date2
* @return int
*/
public static int daysBetween(Date date1,Date date2) {
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
long time1 = cal.getTimeInMillis();
cal.setTime(date2);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1);
return Integer.parseInt(String.valueOf(between_days/1000));
}
/**
* @Description: 获取当前日期是星期几
* @param date
* @return String
*/
public static String getWeekOfDate(Date date) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* @Description: 获取当前月是几月
* @param date
* @return String
*/
public static String getMonthOfDate(Date date) {
String[] month = {"一月份", "二月份", "三月份", "四月份", "五月份", "六月份", "七月份", "八月份", "九月份", "十月份", "十一月份", "十二月份"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int m = cal.get(Calendar.MONTH);
if (m < 0)
m = 0;
return month[m];
}
/**
*函数描述:比较日期
* @param date1 日期1
* @param date2 日期2
* @return 当date1大时返回 1 当相等时返回0 其他为-1
*/
public static int compareDate(Date date1 ,Date date2)
{
int outInt =0;
if(date1.after(date2))
{
outInt =1;
}
if(date1.before(date2))
{
outInt =-1;
}
return outInt;
}
/**
* @Description: 获取当前时间距离今日凌晨的秒数
* @return int
*/
public static int nowToBeginSecond(){
long time = new Date().getTime();
Timestamp timestamp = new Timestamp(time);
String timesString = timestamp + "";
String[] a = timesString.split(" ");
String[] b=a[1].split("\\.");
String[] c=b[0].split(":");
return Integer.valueOf(c[0])*60*60 + Integer.valueOf(c[1])*60 + Integer.valueOf(c[2]);
}
/**
* @Description: 判断两个日期是否在同一周
* @param date1
* @param date2
* @return boolean
*/
public static boolean isSameWeek(Date date1,Date date2){
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR)-cal2.get(Calendar.YEAR);
//subYear==0,说明是同一年
if(subYear == 0){
//i1每年的第几周: 英文周日为第一天 判断为周日时 需要将每年的星期数-1
int w1 = cal1.get(Calendar.DAY_OF_WEEK) - 1;
int w2 = cal2.get(Calendar.DAY_OF_WEEK) - 1;
int i1 = cal1.get(Calendar.WEEK_OF_YEAR);
int i2 = cal2.get(Calendar.WEEK_OF_YEAR);
//weekDay == 0 证明是周日
if(w1==0)
i1=i1-1;
if(w2==0)
i2=i2-1;
if(i1 == i2)
return true;
}
return false;
}
/**
* 函数描述:将给定日期的时分秒清零
* @param date 指定的日期
* @return
*/
public static Date getZero(Date date){
return getZero(date,0);
}
/**
* 函数描述:将给定日期增减(N)天后的时分秒清零
* @param date 指定日期
* @param days 增减的天数
* @return
*/
public static Date getZero(Date date, int days){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, days);//天数+n
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);//毫秒置0
Date newDate = calendar.getTime();//得到新的date对象.
return newDate;
}
/**
* 函数描述:将给定日期增减(N)天后的时分秒清零
* @param date 指定日期
* @param days 增减的天数
* @return
*/
public static Date getZero(Date date, int years,int months,int days){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, years);//年数+n
calendar.add(Calendar.MONTH, months);//月数+n
calendar.add(Calendar.DATE, days);//天数+n
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);//毫秒置0
Date newDate = calendar.getTime();//得到新的date对象.
return newDate;
}
/***
* 根据日历的规则,为给定的日历字段添加或减去指定的时间量。并返回指定日期格式
* @param field
* @param amount
* @return
*/
public static Date addTime(int field, int amount,Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(field, amount);
return calendar.getTime();
}
/**
* 计算是否会员及会员剩余天数
* @param memberTime 会员到期时间
* @return object[0] 是否会员
* object[1]会员剩余天数
*/
public static Object[] isMember(Date memberTime){
int day=0;
boolean isMember = false;
if(memberTime!=null){
day = DateUtil.daysBetween(new Date(), memberTime);
if(day>0){
isMember = true;
}
day = Integer.parseInt(String.valueOf(day/(3600*24)));
}
return new Object[]{isMember,day};
}
/**
* 获取1970-01-01日期格式
* @return
*/
public static Date getFirstDate(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
try {
Date date =df.parse("1970-01-01");
return date;
} catch (ParseException e) {
}
return null;
}
/**
* @Description: 获取本月开始时间
* @return String
*/
public static String getFirstDayOfMonth(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//获取当前月第一天:
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
return format.format(c.getTime());
}
/**
* @Description: 获取本月的结束时间
* @return String
*/
public static String getLastDayOfMonth(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
return format.format(ca.getTime());
}
public static int compare_date(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
System.out.println("dt1 在dt2后");
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
System.out.println("dt1在dt2前");
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static int compare_date(Date DATE1, Date DATE2) {
try {
Date dt1 = DATE1;
Date dt2 = DATE2;
if (dt1.getTime() > dt2.getTime()) {
System.out.println("dt1 在dt2后");
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
System.out.println("dt1在dt2前");
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static int compare_date(String DATE1, String DATE2, String DATE3) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
Date dt3 = df.parse(DATE3);
if (dt1.getTime() > dt2.getTime() && dt1.getTime() < dt3.getTime()) {
System.out.println("dt1 在dt2和dt3之间");
return 1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
/**
* 判断是否同一天
* @param date1
* @param date2
* @return boolean
*/
public static boolean isSameDay(Date date1,Date date2){
String sdate1 = getDate(date1);
String sdate2 = getDate(date2);
if(sdate1.equals(sdate2))
return true;
else
return false;
}
/**
* @Description: 获取n天后的时间戳
* @param n
* @return long
*/
public static long nextDays(int n) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, n);
return calendar.getTimeInMillis();
}
public static Date nextHours(int n, Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, n);
return calendar.getTime();
}
public static Date nextMinute(int n, Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, n);
return calendar.getTime();
}
public static Date nextSecond(int n, Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, n);
return calendar.getTime();
}
public static Date nextDate(int n, Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, n);
return calendar.getTime();
}
/**
* @Description: 获取当前日期的上月日期
* @return String
*/
public static String lastMonth(){
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
Date date = c.getTime();
return getDate(date, "yyyy-MM-dd");
}
/**
* @Description: 获取当前日期的年份后两位
* @return Integer
*/
public static Integer year2(){
return Integer.parseInt(new SimpleDateFormat("yy",Locale.CHINESE).format(Calendar.getInstance().getTime()));
}
//获取token刷新时间
public static Date getTokenActiveTime() {
return new Date(System.currentTimeMillis()+30*24*60*60*1000);
}
/**
* @Description: 获取当前时间前n年或者后n年
* @param date
* @param year
* @return Date
*/
public static Date getYearDate(Date date,Integer n) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, n);
Date y = c.getTime();
return y;
}
}
在添加了LocalDate和LocalDateTime之后,新增了几个方法
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
/**
* 日期处理
*/
public class DateUtils {
/** 时间格式(yyyy-MM-dd) */
public final static String DATE_PATTERN = "yyyy-MM-dd";
/** 时间格式(yyyy-MM-dd HH:mm:ss) */
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String format(Date date) {
return format(date, DATE_PATTERN);
}
public static String formatDateTime(Date date) {
return format(date, DATE_TIME_PATTERN);
}
public static String format(Timestamp timestamp) {
Date date = new Date(timestamp.getTime());
return format(date, DATE_TIME_PATTERN);
}
public static String format(Date date, String pattern) {
if(date != null){
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
return null;
}
public static Date parseDate(String dateStr, String pattern) {
if (StringUtils.isNotBlank(dateStr)) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
try {
return df.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 年月日字符串时间格式化
* @param dateStr 年月日
* @param pattern yyyy-MM-dd
* @return LocalDate
*/
public static LocalDate parseLocalDate(String dateStr) {
if (StringUtils.isNotBlank(dateStr)) {
if (dateStr.length() > 10) {
dateStr = dateStr.substring(0, 10);
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_PATTERN);
LocalDate localDate = LocalDate.parse(dateStr, formatter);
return localDate;
}
return null;
}
/**
* 年月日时分秒 字符串时间格式化
* @param dateStr 年月日时分秒
* @param pattern yyyy-MM-dd HH:mm:ss
* @return LocalDateTime
*/
public static LocalDateTime parseLocalDateTime(String dateStr) {
if (StringUtils.isNotBlank(dateStr)) {
if (dateStr.length() < 19) {
dateStr = dateStr.substring(0, 10) + " 00:00:00";
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);
return localDateTime;
}
return null;
}
/**
* 格式化日期
* @param localDate
* @return yyyy-MM-dd
*/
public static String format(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_PATTERN);
return localDate.format(formatter).toString();
}
/**
* 格式化日期时间
* @param localDateTime
* @return yyyy-MM-dd HH:mm:ss
*/
public static String format(LocalDateTime localDateTime) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
return localDateTime.format(formatter).toString();
}
/**
* Date转换为LocalDateTime
* @param date
*/
public static LocalDateTime date2LocalDateTime(Date date){
Instant instant = date.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
return localDateTime;
}
/**
* LocalDateTime转换为Date
* @param localDateTime
*/
public static Date localDateTime2Date( LocalDateTime localDateTime){
ZoneId zoneId = ZoneId.systemDefault();
//Combines this date-time with a time-zone to create a ZonedDateTime.
ZonedDateTime zdt = localDateTime.atZone(zoneId);
Date date = Date.from(zdt.toInstant());
return date;
}
public static void main(String[] args) {
String string = "2019-10-11 11";
System.out.println(string.length());
// LocalDateTime parse = LocalDateTime.parse(string);
// System.out.println(parse);
// Date localDateTime2Date = localDateTime2Date(parse);
// System.out.println(localDateTime2Date);
// LocalDate parseLocalDate = parseLocalDate(string);
// System.out.println(parseLocalDate);
LocalDateTime parseLocalDateTime = parseLocalDateTime(string);
System.out.println(format(parseLocalDateTime));
}
}