日期共通类实现

Posted 霄九天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日期共通类实现相关的知识,希望对你有一定的参考价值。

我们经常会遇到日期的处理需求,以下是工作中编写的日期共通类

package com.gomecar.index.common.utils;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateUtil {

    private static Logger logger = Logger.getLogger(DateUtil.class);
    public static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE = "yyyy-MM-dd";

    public static String datetimeToStr(final Date date, final String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static String dateTimeToStr(final Date date) {
        return DateUtil.datetimeToStr(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String dateToStr(final Date date) {
        return DateUtil.datetimeToStr(date, "yyyy-MM-dd");
    }

    public static String dateToStr(final Date date, String format) {
        return DateUtil.datetimeToStr(date, format);
    }

    public static String getCurrentDate() {
        return new SimpleDateFormat(DATE).format(new Date());
    }

    public static String getCurrentDate(String format) {
        return new SimpleDateFormat(format).format(new Date());
    }

    public static String getCurrentDatetime() {
        return new SimpleDateFormat(DATETIME).format(new Date());
    }

    public static String getCurrentDatetime(String format) {
        return new SimpleDateFormat(format).format(new Date());
    }

    public static int getCurrentTimeHashCode() {
        return String.valueOf(System.currentTimeMillis()).hashCode();
    }

    /**
     * 获得当前时间当天的开始时间,即当前给出的时间那一天的00:00:00的时间
     * 
     * @param date
     *            当前给出的时间
     * @return 当前给出的时间那一天的00:00:00的时间的日期对象
     */
    public static Date getDateBegin(final Date date) {
        SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (date != null) {
            try {
                return DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINA).parse(ymdFormat.format(date));
            } catch (ParseException e) {
                logger.error("DataFromat error");
            }
        }
        return null;
    }

    public static Date getDateEnd(Date date) {
        SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (date != null) {
            try {
                Date endDate = strToDate(ymdFormat.format(new Date(date.getTime() + 24 * 60 * 60 * 1000)));
                endDate = new Date(endDate.getTime() - 1000);
                return endDate;
            } catch (Exception e) {
                logger.error("DataFromat error");
            }
        }
        return null;
    }

    public static long getNow() {
        return System.currentTimeMillis();
    }

    public static String getTime() {
        Date d = new Date();
        String re = datetimeToStr(d, "yyyyMMddHHmmssSSS");
        return re;
    }

    
    public static String getTime(String format) {
        Date d = new Date();
        String re = datetimeToStr(d, format);
        return re;
    }

    public static Date strToFormatDate(final String date, final String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(date, new ParsePosition(0));
    }

    public static Date strToDate(final String date) {
        return DateUtil.strToFormatDate(date, "yyyy-MM-dd");
    }

    public static final Date strToDate(final String dateStr, final String format) {
        return DateUtil.strToFormatDate(dateStr, format);
    }

    public static Date strToDateTime(final String date) {
        return DateUtil.strToFormatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date strToDateTime(final String date, final String format) {
        return DateUtil.strToFormatDate(date, format);
    }

    public static Timestamp strToTimestamp(String str) throws Exception {
        if (StringUtils.isEmpty(str)) {
            throw new Exception("转换错误");
        }
        if (str.trim().length() > 10) {
            return new Timestamp(new SimpleDateFormat(DATETIME).parse(str).getTime());
        } else {
            return new Timestamp(new SimpleDateFormat(DATE).parse(str).getTime());
        }
    }

    public static Timestamp strToTimestamp(String sDate, String sFormat) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(sFormat);
        Date t = sdf.parse(sDate);
        return new Timestamp(t.getTime());

    }

    public static boolean validateExpireDate(final long timeMillis, final long expireTimeMillis) {
        return (getNow() - timeMillis) > expireTimeMillis;
    }

    //秒换算成时分秒
    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }
    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }

    /**
     * 获取时间差
     * @param timeMillis
     * @return
     */
    public  static  String  getLastTime(long timeMillis){

        if (timeMillis<=0){
           return "-1";
        }
        String time="";
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1 = df.parse(getYearMonthDayHourMinuteSecond(System.currentTimeMillis()+timeMillis));
            Date d2 = new Date();
            long date = d1.getTime() - d2.getTime();
            long day = date / (1000 * 60 * 60 * 24);
            long hour = (date / (1000 * 60 * 60) - day * 24);
            long min = ((date / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long s = (date/1000 - day*24*60*60 - hour*60*60 - min*60);
            time = day+"天"+hour+"小时"+min+"分"+s+"秒";
            //System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
        }catch (Exception e) {
            return "-1";
        }
        return time;
    }

    public  static  String getYearMonthDayHourMinuteSecond(long timeMillis) {
        int timezone = 8; // 时区
        long totalSeconds = timeMillis / 1000;
        totalSeconds += 60 * 60 * timezone;
        int second = (int) (totalSeconds % 60);//
        long totalMinutes = totalSeconds / 60;
        int minute = (int) (totalMinutes % 60);//
        long totalHours = totalMinutes / 60;
        int hour = (int) (totalHours % 24);//
        int totalDays = (int) (totalHours / 24);
        int _year = 1970;
        int year = _year + totalDays / 366;
        int month = 1;
        int day = 1;
        int diffDays;
        boolean leapYear;
        while (true) {
            int diff = (year - _year) * 365;
            diff += (year - 1) / 4 - (_year - 1) / 4;
            diff -= ((year - 1) / 100 - (_year - 1) / 100);
            diff += (year - 1) / 400 - (_year - 1) / 400;
            diffDays = totalDays - diff;
            leapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
            if (!leapYear && diffDays < 365 || leapYear && diffDays < 366) {
                break;
            } else {
                year++;
            }
        }

        int[] monthDays;
        if (diffDays >= 59 && leapYear) {
            monthDays = new int[] { -1, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
        } else {
            monthDays = new int[] { -1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
        }
        for (int i = monthDays.length - 1; i >= 1; i--) {
            if (diffDays >= monthDays[i]) {
                month = i;
                day = diffDays - monthDays[i] + 1;
                break;
            }
        }
        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    }
}

 

以上是关于日期共通类实现的主要内容,如果未能解决你的问题,请参考以下文章

JUnit套件测试(共通类测试)

在片段中创建日期选择器

常用python日期日志获取内容循环的代码片段

JS代码片段:一个日期离现在多久了

sql 日期转换代码片段 - Dato,120,konvertere

材料管理框架:一个共通的viewModel搞定所有的分页查询