一: 时间格式工具类
package utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
/**
* 时间工具类
* @author Administrator
*
*/
public class DateUtil {
private static Logger log = LoggerFactory.getLogger( DateUtil.class );
public static final String PATTERN_STANDARD = "yyyy-MM-dd HH:mm:ss";
public static final String PATTERN_DATE_S = "yyyyMMdd";
/**
* 时间戳(秒)转化为Sting
* @return 默认返回0
*/
public static String dateFormat( Integer time) {
try {
long longValue = time.longValue();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d = format.format(longValue*1000);
return d;
} catch ( Exception e ) {
log.error( e.getMessage() , e );
}
return "0";
}
/**
* 时间戳(毫秒)转化为Sting
* @return 默认返回0
*/
public static String lsndateFormat( Long time) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d = format.format(time);
return d;
} catch ( Exception e ) {
log.error( e.getMessage() , e );
}
return "0";
}
/**
* 时间戳(毫秒)转化为Sting
* @return 默认返回0
*/
public static String lsndateFormat( Long time,String formatStr) {
try {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
String d = format.format(time);
return d;
} catch ( Exception e ) {
log.error( e.getMessage() , e );
}
return "0";
}
/**
* 字符串转时间戳(毫秒)
* @param time
* @return
*/
public static String lsnParseTime(String time){
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
try {
long time1 = format.parse(time).getTime();
return String.valueOf(time1);
} catch (ParseException e) {
e.printStackTrace();
}
return "0";
}
public static Long lsnStarttime(Long time){
if(time==null){
return null;
}
Date date = dateFormat(time);
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.set(Calendar.HOUR_OF_DAY, 0);
instance.set(Calendar.MINUTE, 0);
instance.set(Calendar.SECOND, 0);
instance.set(Calendar.MILLISECOND, 0);
long timeInMillis = instance.getTimeInMillis();
return timeInMillis;
}
public static Long lsnEndtime(Long time){
if(time==null){
return null;
}
Date date = dateFormat(time);
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.set(Calendar.HOUR_OF_DAY, 23);
instance.set(Calendar.MINUTE, 59);
instance.set(Calendar.SECOND, 59);
instance.set(Calendar.MILLISECOND, 999);
long timeInMillis = instance.getTimeInMillis();
return timeInMillis;
}
/**
* 时间戳(秒)转化为Sting
* @return 默认返回0
*/
public static String dateFormats( Integer time) {
try {
long longValue = time.longValue();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String d = format.format(longValue*1000);
return d;
} catch ( Exception e ) {
log.error( e.getMessage() , e );
}
return "0";
}
/**
* 获取当天开始的时间
* @return
*/
public static String getStartTime() {
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
long timeInMillis = todayStart.getTimeInMillis();
return String.valueOf(timeInMillis / 1000);
}
/**
* 获取当天结束时间
* @return
*/
public static String getnowEndTime() {
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR_OF_DAY, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
long timeInMillis = todayEnd.getTimeInMillis();
return String.valueOf(timeInMillis / 1000);
}
/**
* 获取本周周一0点的时间
* @return
*/
public static String getTimesWeekmorning() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
long timeInMillis = cal.getTimeInMillis();
return String.valueOf(timeInMillis / 1000);
}
// 获得本周日24点时间
public static String getTimesWeeknight() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.add(Calendar.DAY_OF_WEEK, 7);
long timeInMillis = cal.getTimeInMillis();
return String.valueOf(timeInMillis / 1000);
}
// 获得本月第一天0点时间
public static String getTimesMonthmorning() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
long timeInMillis = cal.getTimeInMillis();
return String.valueOf(timeInMillis / 1000);
}
// 获得本月最后一天24点时间
public static String getTimesMonthnight() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 24);
long timeInMillis = cal.getTimeInMillis();
return String.valueOf(timeInMillis / 1000);
}
/**
* 当前日期
* @param timestamp
* @param pattern
* @return
*/
public static String timestamp2String(Timestamp timestamp, String pattern) {
if (timestamp == null) {
throw new IllegalArgumentException("timestamp null illegal");
}
if (pattern == null || pattern.equals("")) {
pattern = PATTERN_STANDARD;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(new Date(timestamp.getTime()));
}
public static String currentTimestamp2String(String pattern) {
return timestamp2String(currentTimestamp(), pattern);
}
public static Timestamp currentTimestamp() {
return new Timestamp(new Date().getTime());
}
/**
* Sting转化为date
* @return 默认返回0
*/
public static Date dateFormat(String time) {
Date date = null;
try {
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
date = formatter.parse(time);
} catch ( Exception e ) {
log.error( e.getMessage() , e );
}
return date;
}
/**
* Sting转化为date
* @return 默认返回0
*/
public static Date dateFormatStr(String time) {
if(StringUtils.isBlank(time)){
return null;
}
Date date = null;
try {
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟
date = formatter.parse(time);
} catch ( Exception e ) {
log.error( e.getMessage() , e );
}
return date;
}
/**
* 时间戳转化为date
* @return 默认返回null
*/
public static Date dateFormat(Long time) {
Date date = null;
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d = format.format(time);
date = format.parse(d);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return date;
}
/**
* 判断两个时间戳是不是同一天
* @param time1
* @param time2
* @return
*/
public static Boolean comparetimestampByDate(Long time1,Long time2){
Date date1 = dateFormat(time1);
Date date2 = dateFormat(time2);
int i = daysBetween(date1, date2);
if(i == 0){
return true;
}else {
return false;
}
}
/**
* 时间戳转化为String
* @return 默认返回null
*/
public static String StringFormat(Long time) {
String d = "";
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
d = format.format(time);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return d;
}
/**
*获取日期之间的天数
*/
public static int daysBetween(Date now, Date returnDate) {
Calendar cNow = Calendar.getInstance();
Calendar cReturnDate = Calendar.getInstance();
cNow.setTime(now);
cReturnDate.setTime(returnDate);
setTimeToMidnight(cNow);
setTimeToMidnight(cReturnDate);
long todayMs = cNow.getTimeInMillis();
long returnMs = cReturnDate.getTimeInMillis();
long intervalMs = todayMs - returnMs;
return millisecondsToDays(intervalMs);
}
private static int millisecondsToDays(long intervalMs) {
return (int) (intervalMs / (1000 * 86400));
}
private static void setTimeToMidnight(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
}
/**
* 添加指定时间天数
*/
public static Date getAfterData(Date date, int count) {
Date d = null;
d = new Date(date.getTime() + count * 24 * 60 * 60 * 1000L);
return d;
}
/**
* 判断日期是否符合指定格式
* @param str 日期字符串
* @param format 日期格式
* @return
*/
public static boolean isValidDate(String str,String format) {
boolean convertSuccess = true;
SimpleDateFormat sf = new SimpleDateFormat(format);
try {
if (str.trim().length() != sf.toPattern().length())
return false;
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
sf.setLenient(false);
sf.parse(str);
} catch (Exception e) {
// e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
convertSuccess = false;
}
return convertSuccess;
}
//输入 yyyy-MM-dd 或 yyyy/MM/dd 或 yyyyMMdd 的日期格式 ,返回 yyyy-MM-dd 类型的日期字符串
public static String converDate(String dateStr) {
if(dateStr == null){
return null;
}
if(StringUtils.isBlank(dateStr)){
return "";
}
if(DateUtil.isValidDate(dateStr, "yyyy-MM-dd")){
return dateStr;
}
try{
if(DateUtil.isValidDate(dateStr, "yyyyMMdd")){
Date date = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(dateStr));
dateStr = DateUtil.dateFormatToStr(date,"yyyy-MM-dd");
return dateStr;
}
if(DateUtil.isValidDate(dateStr, "yyyy/MM/dd")){
Date date = new SimpleDateFormat("yyyy/MM/dd").parse(String.valueOf(dateStr));
dateStr = DateUtil.dateFormatToStr(date,"yyyy-MM-dd");
return dateStr;
}
}catch (Exception e){
e.printStackTrace();
dateStr = "123456"; //如果日期格式不满足以上要求,就返回一个错误的日期格式。
}
return dateStr;
}
//返回当前时间的字符串形式。用于文件上传的名字重命名用。防止文件名重复。
public static String convertNowToStr(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String str = null;
str = sdf.format(new Date());
return str;
}
//输入yyyyMMddHHmmss字符串返回yyyy-MM-dd HH:mm:ss
public static String getDateString(String str){
String reg = "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})";
str = str.replaceAll(reg, "$1-$2-$3 $4:$5:$6");
return str;
}
public static Long getTimes(Date date){
if(date == null){
return 0L;
}
return date.getTime();
}
//判断两个时间大小
public static boolean timeThan(Date date1,Date date2){
if(getTimes(date1) > getTimes(date2)){
return true;
}
return false;
}
//获得 指定近几个月的 日期集合
public static ArrayList<String> getLateMonth(int month) throws ParseException{
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -(month-2));
String before_six=c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);//六个月前
ArrayList<String> result = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
min.setTime(sdf.parse(before_six));
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(sdf.parse(sdf.format(new Date())));
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);
}
//System.out.println(result);
return result;
}
/**
* date转化为Sting
* @return 默认返回0
*/
public static String dateFormatToStr(Date date , String pattern) {
if(date == null){
return "";
}
String str = "";
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
str = sdf.format(date);
} catch ( Exception e ) {
log.error( e.getMessage() , e );
}
return str;
}
/**
* 获取时间戳
*/
public static String getTimeString() {
SimpleDateFormat df = new SimpleDateFormat(PATTERN_STANDARD);
Calendar calendar = Calendar.getInstance();
return df.format(calendar.getTime());
}
/**
* 获取日期年份
* @param date 日期
* @return
*/
public static String getYear(Date date) {
SimpleDateFormat sf = new SimpleDateFormat(PATTERN_STANDARD);
return sf.format(date).substring(0, 4);
}
/**
* 功能描述:返回月
*
* @param date
* Date 日期
* @return 返回月份
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 功能描述:返回日
*
* @param date
* Date 日期
* @return 返回日份
*/
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 功能描述:返回小
*
* @param date
* 日期
* @return 返回小时
*/
public static int getHour(Date date) {
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
/**
* 功能描述:返回分
*
* @param date
* 日期
* @return 返回分钟
*/
public static int getMinute(Date date) {
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MINUTE);
}
/**
* 返回秒钟
*
* @param date
* Date 日期
* @return 返回秒钟
*/
public static int getSecond(Date date) {
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.SECOND);
}
/**
* 功能描述:返回毫
*
* @param date
* 日期
* @return 返回毫
*/
public static long getMillis(Date date) {
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getTimeInMillis();
}
}