Java日期工具類

jopen 12年前發布 | 39K 次閱讀 Java Java開發

public class DateUtil
{
    //默認顯示日期的格式
    public static final String DATAFORMAT_STR = "yyyy-MM-dd";

//默認顯示日期的格式
public static final String YYYY_MM_DATAFORMAT_STR = "yyyy-MM";

//默認顯示日期時間的格式
public static final String DATATIMEF_STR = "yyyy-MM-dd HH:mm:ss";

//默認顯示簡體中文日期的格式
public static final String ZHCN_DATAFORMAT_STR = "yyyy年MM月dd日";

//默認顯示簡體中文日期時間的格式
public static final String ZHCN_DATATIMEF_STR = "yyyy年MM月dd日HH時mm分ss秒";

//默認顯示簡體中文日期時間的格式
public static final String ZHCN_DATATIMEF_STR_4yMMddHHmm = "yyyy年MM月dd日HH時mm分";

private static DateFormat dateFormat = null;

private static DateFormat dateTimeFormat = null;

private static DateFormat zhcnDateFormat = null;

private static DateFormat zhcnDateTimeFormat = null;
static
{
    dateFormat = new SimpleDateFormat(DATAFORMAT_STR);
    dateTimeFormat = new SimpleDateFormat(DATATIMEF_STR);
    zhcnDateFormat = new SimpleDateFormat(ZHCN_DATAFORMAT_STR);
    zhcnDateTimeFormat = new SimpleDateFormat(ZHCN_DATATIMEF_STR);
}

private static DateFormat getDateFormat(String formatStr)
{
    if (formatStr.equalsIgnoreCase(DATAFORMAT_STR))
    {
        return dateFormat;
    }
    else
        if (formatStr.equalsIgnoreCase(DATATIMEF_STR))
        {
            return dateTimeFormat;
        }
        else
            if (formatStr.equalsIgnoreCase(ZHCN_DATAFORMAT_STR))
            {
                return zhcnDateFormat;
            }
            else
                if (formatStr.equalsIgnoreCase(ZHCN_DATATIMEF_STR))
                {
                    return zhcnDateTimeFormat;
                }
                else
                {
                    return new SimpleDateFormat(formatStr);
                }
}

/**
 * 按照默認顯示日期時間的格式"yyyy-MM-dd HH:mm:ss",轉化dateTimeStr為Date類型
 * dateTimeStr必須是"yyyy-MM-dd HH:mm:ss"的形式
 * @param dateTimeStr
 * @return
 */
public static Date getDate(String dateTimeStr)
{
    return getDate(dateTimeStr, DATATIMEF_STR);
}

/**
 * 按照默認formatStr的格式,轉化dateTimeStr為Date類型
 * dateTimeStr必須是formatStr的形式
 * @param dateTimeStr
 * @param formatStr
 * @return
 */
public static Date getDate(String dateTimeStr, String formatStr)
{
    try
    {
        if (dateTimeStr == null || dateTimeStr.equals(""))
        {
            return null;
        }
        DateFormat sdf = getDateFormat(formatStr);
        java.util.Date d = sdf.parse(dateTimeStr);
        return d;
    }
    catch (ParseException e)
    {
        throw new RuntimeException(e);
    }
}

/**
 * 將YYYYMMDD轉換成Date日期
 * @param date
 * @return
 * @throws BusinessException
 */
public static Date transferDate(String date) throws Exception
{
    if (date == null || date.length() < 1)
        return null;

    if (date.length() != 8)
        throw new Exception("日期格式錯誤");
    String con = "-";

    String yyyy = date.substring(0, 4);
    String mm = date.substring(4, 6);
    String dd = date.substring(6, 8);

    int month = Integer.parseInt(mm);
    int day = Integer.parseInt(dd);
    if (month < 1 || month > 12 || day < 1 || day > 31)
        throw new Exception("日期格式錯誤");

    String str = yyyy + con + mm + con + dd;
    return DateUtil.getDate(str, DateUtil.DATAFORMAT_STR);
}

/**
 * 將YYYY-MM-DD日期轉換成yyyymmdd格式字符串
 * @param date
 * @return
 */
public static String getYYYYMMDDDate(Date date)
{
    if (date == null)
        return null;
    String yyyy = getYear(date) + "";
    String mm = getMonth(date) + "";
    String dd = getDay(date) + "";

    mm = StringUtil.rightAlign(mm, 2, "0");
    dd = StringUtil.rightAlign(dd, 2, "0");
    return yyyy + mm + dd;
}

/**
 * 將YYYY-MM-DD日期轉換成YYYYMMDDHHMMSS格式字符串
 * @param date
 * @return
 */
public static String getYYYYMMDDHHMMSSDate(Date date)
{
    if (date == null)
        return null;
    String yyyy = getYear(date) + "";
    String mm = getMonth(date) + "";
    String dd = getDay(date) + "";
    String hh = getHour(date) + "";
    String min = getMin(date) + "";
    String ss = getSecond(date) + "";

    mm = StringUtil.rightAlign(mm, 2, "0");
    dd = StringUtil.rightAlign(dd, 2, "0");
    hh = StringUtil.rightAlign(hh, 2, "0");
    min = StringUtil.rightAlign(min, 2, "0");
    ss = StringUtil.rightAlign(ss, 2, "0");

    return yyyy + mm + dd + hh + min + ss;
}

/**
 * 將YYYY-MM-DD日期轉換成yyyymmdd格式字符串
 * @param date
 * @return
 */
public static String getYYYYMMDDDate(String date)
{
    return getYYYYMMDDDate(getDate(date, DATAFORMAT_STR));
}

/**
 * 將Date轉換成字符串“yyyy-mm-dd hh:mm:ss”的字符串
 * @param date
 * @return
 */
public static String dateToDateString(Date date)
{
    return dateToDateString(date, DATATIMEF_STR);
}

/**
 * 將Date轉換成formatStr格式的字符串
 * @param date
 * @param formatStr
 * @return
 */
public static String dateToDateString(Date date, String formatStr)
{
    DateFormat df = getDateFormat(formatStr);
    return df.format(date);
}

/**
 * 返回一個yyyy-MM-dd HH:mm:ss 形式的日期時間字符串中的HH:mm:ss
 * @param dateTime
 * @return
 */
public static String getTimeString(String dateTime)
{
    return getTimeString(dateTime, DATATIMEF_STR);
}

/**
 * 返回一個formatStr格式的日期時間字符串中的HH:mm:ss
 * @param dateTime
 * @param formatStr
 * @return
 */
public static String getTimeString(String dateTime, String formatStr)
{
    Date d = getDate(dateTime, formatStr);
    String s = dateToDateString(d);
    return s.substring(DATATIMEF_STR.indexOf('H'));
}

/**
 * 獲取當前日期yyyy-MM-dd的形式
 * @return
 */
public static String getCurDate()
{
    //return dateToDateString(new Date(),DATAFORMAT_STR);
    return dateToDateString(Calendar.getInstance().getTime(), DATAFORMAT_STR);
}

/**
 * 獲取當前日期yyyy年MM月dd日的形式
 * @return
 */
public static String getCurZhCNDate()
{
    return dateToDateString(new Date(), ZHCN_DATAFORMAT_STR);
}

/**
 * 獲取當前日期時間yyyy-MM-dd HH:mm:ss的形式
 * @return
 */
public static String getCurDateTime()
{
    return dateToDateString(new Date(), DATATIMEF_STR);
}

/**
 * 獲取當前日期時間yyyy年MM月dd日HH時mm分ss秒的形式
 * @return
 */
public static String getCurZhCNDateTime()
{
    return dateToDateString(new Date(), ZHCN_DATATIMEF_STR);
}

/**
 * 獲取日期d的days天后的一個Date
 * @param d
 * @param days
 * @return
 */
public static Date getInternalDateByDay(Date d, int days)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    now.add(Calendar.DATE, days);
    return now.getTime();
}

public static Date getInternalDateByMon(Date d, int months)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    now.add(Calendar.MONTH, months);
    return now.getTime();
}

public static Date getInternalDateByYear(Date d, int years)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    now.add(Calendar.YEAR, years);
    return now.getTime();
}

public static Date getInternalDateBySec(Date d, int sec)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    now.add(Calendar.SECOND, sec);
    return now.getTime();
}

public static Date getInternalDateByMin(Date d, int min)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    now.add(Calendar.MINUTE, min);
    return now.getTime();
}

public static Date getInternalDateByHour(Date d, int hours)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    now.add(Calendar.HOUR_OF_DAY, hours);
    return now.getTime();
}

/**
 * 根據一個日期字符串,返回日期格式,目前支持4種
 * 如果都不是,則返回null
 * @param DateString
 * @return
 */
public static String getFormateStr(String DateString)
{
    String patternStr1 = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}"; //"yyyy-MM-dd"
    String patternStr2 = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}\\s[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}"; //"yyyy-MM-dd HH:mm:ss";
    String patternStr3 = "[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日";//"yyyy年MM月dd日"
    String patternStr4 = "[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日[0-9]{1,2}時[0-9]{1,2}分[0-9]{1,2}秒";//"yyyy年MM月dd日HH時mm分ss秒"

    Pattern p = Pattern.compile(patternStr1);
    Matcher m = p.matcher(DateString);
    boolean b = m.matches();
    if (b)
        return DATAFORMAT_STR;
    p = Pattern.compile(patternStr2);
    m = p.matcher(DateString);
    b = m.matches();
    if (b)
        return DATATIMEF_STR;

    p = Pattern.compile(patternStr3);
    m = p.matcher(DateString);
    b = m.matches();
    if (b)
        return ZHCN_DATAFORMAT_STR;

    p = Pattern.compile(patternStr4);
    m = p.matcher(DateString);
    b = m.matches();
    if (b)
        return ZHCN_DATATIMEF_STR;
    return null;
}

/**
 * 將一個"yyyy-MM-dd HH:mm:ss"字符串,轉換成"yyyy年MM月dd日HH時mm分ss秒"的字符串
 * @param dateStr
 * @return
 */
public static String getZhCNDateTime(String dateStr)
{
    Date d = getDate(dateStr);
    return dateToDateString(d, ZHCN_DATATIMEF_STR);
}

/**
 * 將一個"yyyy-MM-dd"字符串,轉換成"yyyy年MM月dd日"的字符串
 * @param dateStr
 * @return
 */
public static String getZhCNDate(String dateStr)
{
    Date d = getDate(dateStr, DATAFORMAT_STR);
    return dateToDateString(d, ZHCN_DATAFORMAT_STR);
}

/**
 * 將dateStr從fmtFrom轉換到fmtTo的格式
 * @param dateStr
 * @param fmtFrom
 * @param fmtTo
 * @return
 */
public static String getDateStr(String dateStr, String fmtFrom, String fmtTo)
{
    Date d = getDate(dateStr, fmtFrom);
    return dateToDateString(d, fmtTo);
}

/**
 * 比較兩個"yyyy-MM-dd HH:mm:ss"格式的日期,之間相差多少毫秒,time2-time1
 * @param time1
 * @param time2
 * @return
 */
public static long compareDateStr(String time1, String time2)
{
    Date d1 = getDate(time1);
    Date d2 = getDate(time2);
    return d2.getTime() - d1.getTime();
}

/**
 * 將小時數換算成返回以毫秒為單位的時間
 * @param hours
 * @return
 */
public static long getMicroSec(BigDecimal hours)
{
    BigDecimal bd;
    bd = hours.multiply(new BigDecimal(3600 * 1000));
    return bd.longValue();
}

/**
 * 獲取Date中的分鐘
 * @param d
 * @return
 */
public static int getMin(Date d)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    return now.get(Calendar.MINUTE);
}

/**
 * 獲取Date中的小時(24小時)
 * @param d
 * @return
 */
public static int getHour(Date d)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    return now.get(Calendar.HOUR_OF_DAY);
}

/**
 * 獲取Date中的秒
 * @param d
 * @return
 */
public static int getSecond(Date d)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    return now.get(Calendar.SECOND);
}

/**
 * 獲取xxxx-xx-xx的日
 * @param d
 * @return
 */
public static int getDay(Date d)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    return now.get(Calendar.DAY_OF_MONTH);
}

/**
 * 獲取月份,1-12月
 * @param d
 * @return
 */
public static int getMonth(Date d)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    return now.get(Calendar.MONTH) + 1;
}

/**
 * 獲取19xx,20xx形式的年
 * @param d
 * @return
 */
public static int getYear(Date d)
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    now.setTime(d);
    return now.get(Calendar.YEAR);
}

/**
 * 得到d的上個月的年份+月份,如200505
 * @return
 */
public static String getYearMonthOfLastMon(Date d)
{
    Date newdate = getInternalDateByMon(d, -1);
    String year = String.valueOf(getYear(newdate));
    String month = String.valueOf(getMonth(newdate));
    return year + month;
}

/**
 * 得到當前日期的年和月如200509
 * @return String
 */
public static String getCurYearMonth()
{
    Calendar now = Calendar.getInstance(TimeZone.getDefault());
    String DATE_FORMAT = "yyyyMM";
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
    sdf.setTimeZone(TimeZone.getDefault());
    return (sdf.format(now.getTime()));
}

public static Date getNextMonth(String year, String month)
{
    String datestr = year + "-" + month + "-01";
    Date date = getDate(datestr, DATAFORMAT_STR);
    return getInternalDateByMon(date, 1);
}

public static Date getLastMonth(String year, String month)
{
    String datestr = year + "-" + month + "-01";
    Date date = getDate(datestr, DATAFORMAT_STR);
    return getInternalDateByMon(date, -1);
}

/**
 * 得到日期d,按照頁面日期控件格式,如"2001-3-16"
 * @param d
 * @return
 */
public static String getSingleNumDate(Date d)
{
    return dateToDateString(d, DATAFORMAT_STR);
}

/**
 * 得到d半年前的日期,"yyyy-MM-dd"
 * @param d
 * @return
 */
public static String getHalfYearBeforeStr(Date d)
{
    return dateToDateString(getInternalDateByMon(d, -6), DATAFORMAT_STR);
}

/**
 * 得到當前日期D的月底的前/后若干天的時間,<0表示之前,>0表示之后
 * @param d
 * @param days
 * @return
 */
public static String getInternalDateByLastDay(Date d, int days)
{

    return dateToDateString(getInternalDateByDay(d, days), DATAFORMAT_STR);
}

/**
 * 日期中的年月日相加
 *  @param field int  需要加的字段  年 月 日
 * @param amount int 加多少
 * @return String
 */
public static String addDate(int field, int amount)
{
    int temp = 0;
    if (field == 1)
    {
        temp = Calendar.YEAR;
    }
    if (field == 2)
    {
        temp = Calendar.MONTH;
    }
    if (field == 3)
    {
        temp = Calendar.DATE;
    }

    String Time = "";
    try
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance(TimeZone.getDefault());
        cal.add(temp, amount);
        Time = sdf.format(cal.getTime());
        return Time;
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }

}

/**
 * 獲得系統當前月份的天數
 * @return
 */
public static int getCurentMonthDay()
{
    Date date = Calendar.getInstance().getTime();
    return getMonthDay(date);
}

/**
 * 獲得指定日期月份的天數
 * @return
 */
public static int getMonthDay(Date date)
{
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    return c.getActualMaximum(Calendar.DAY_OF_MONTH);

}

/**
 * 獲得指定日期月份的天數  yyyy-mm-dd
 * @return
 */
public static int getMonthDay(String date)
{
    Date strDate = getDate(date, DATAFORMAT_STR);
    return getMonthDay(strDate);

}

public static String getStringDate(Calendar cal)
{

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    return format.format(cal.getTime());
}

/**
 * @param args
 */
public static void main(String[] args)
{
    //      //System.out.print(DateUtil.getDate("04:04:04","HH:mm:ss"));
    //      System.out.print("\n"+DateUtil.getCurZhCNDateTime());
    //      System.out.print("\n"+getFormateStr(DateUtil.getCurDate()));
    //      System.out.print("\n"+compareDateStr("1900-1-1 1:1:2","1900-1-1 1:1:3"));
    //      System.out.print("\n"+getDay(new Date()));
    //      System.out.print("\n"+getMonth(new Date()));
    //      System.out.print("\n"+getYear(new Date()));
    //      System.out.print("\n"+getMin(new Date()));
    ////        System.out.print("\n"+new Date().getSeconds());
    /*Date d1 = new Date(2007,11,30);
    Date d2 = new Date(2007,12,1);
    if(d2.compareTo(d1)>0){
        System.out.println("d2大于d1");
    }else{
        System.out.println("d2小于d1");
    }*/

    System.out.println(addDate(1, 1));
    System.out.println(addDate(2, 1));
    System.out.println(addDate(3, 1));

    System.out.println(getYYYYMMDDHHMMSSDate(new Date()));

    System.out.println(getCurentMonthDay());

}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!