import org.apache.commons.lang3.time.DateUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
public class DataTimeTools {
//dataTimeFormat 自定义设置日期格式
public String getNowDateTime(String dataTimeFormat){
if(dataTimeFormat == null || dataTimeFormat.length()<0)
return getNowDateTime();
SimpleDateFormat df = new SimpleDateFormat(dataTimeFormat);
return df.format(new Date());
}
public String getNowDateTime(){
SimpleDateFormat df = new SimpleDateFormat("yy-MM-dd HH:mm:ss");//设置日期格式
return df.format(new Date());
}
public LocalDate date2LocalDate(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
return localDateTime.toLocalDate();
}
public Date string2Date(String date) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
return format.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String timeStamp2String(String timeStamp, String format) {
if (timeStamp == null || timeStamp.isEmpty() || timeStamp.equals("null")) {
return "";
}
if (format == null || format.isEmpty()) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date(Long.valueOf(timeStamp)));
}
public LocalDate timeStamp2LocalDate(String timeStamp, String format) {
return date2LocalDate(string2Date(timeStamp2String(timeStamp, format)));
}
public Date addDateDays(String dayTime, int days) {
Date to = string2Date(dayTime);
return DateUtils.addDays(to, days);
}
public String addDateHours(String dayTime, int hour) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(dayTime);
} catch (Exception ex) {
ex.printStackTrace();
}
if (date == null)
return "";
System.out.println("front:" + format.format(date)); //显示输入的日期
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, hour);// 24小时制
date = cal.getTime();
System.out.println("after:" + format.format(date)); //显示更新后的日期
return format.format(date);
}
public Date randomDate(String beginDate,String endDate) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date start = format.parse(beginDate);
Date end = format.parse(endDate);
if (start.getTime() >= end.getTime()) {
return null;
}
long date = random(start.getTime(), end.getTime());
return new Date(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public long random(long begin,long end){
long rtn = begin + (long)(Math.random() * (end - begin));
if(rtn == begin || rtn == end){
return random(begin,end);
}
return rtn;
}
}
网友评论