常用的時(shí)間格式化工具整理

···

package com.yql.sdk.util;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.time.Instant;

import java.time.LocalDate;

import java.time.LocalDateTime;

import java.time.LocalTime;

import java.time.ZoneId;

import java.time.temporal.ChronoUnit;

import java.util.Calendar;

import java.util.Date;

import java.util.TimeZone;

import com.panda.sdk.exception.BizException;

public class DateUtils extends org.apache.commons.lang.time.DateUtils {

public static final String FORMAT_DATE_I = "yyyy-MM-dd HH:mm";

public static final String FORMAT_DATE_II = "yyyy/MM/dd HH:mm";

public static final String FORMAT_DATE_AND_TIME_I = "yyyy-MM-dd HH:mm:ss";

public static final String FORMAT_DATE_AND_TIME_II = "yyyy/MM/dd HH:mm:ss";

public static final String FORMAT_ONLY_DATE_I = "yyyy-MM-dd";

public static final String FORMAT_ONLY_DATE_II = "yyyy/MM/dd";

public static String getFormat(String source) {

if (source == null) {

throw new BizException("dateformat is null");

}

String format = null;

if (source.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$")) {

format = FORMAT_DATE_AND_TIME_I;

} else if (source.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}$")) {

format = FORMAT_DATE_AND_TIME_II;

} else if (source.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}$")) {

format = FORMAT_DATE_I;

} else if (source.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}$")) {

format = FORMAT_DATE_II;

} else if (source.matches("^\\d{4}/\\d{2}/\\d{2}$")) {

format = FORMAT_ONLY_DATE_II;

} else if (source.matches("^\\d{4}-\\d{2}-\\d{2}$")) {

format = FORMAT_ONLY_DATE_I;

} else {

throw new BizException("not support this dateformat");

}

return format;

}

/**

* 獲取下一天

*

* @param date

* @return

*/

public static Date getNextDate(Date date) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.set(Calendar.HOUR_OF_DAY, 0);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MILLISECOND, 0);

cal.add(Calendar.DAY_OF_MONTH, 1);

return cal.getTime();

}

/**

* 獲取下一天

*

* @param date

* @return

*/

public static Date getNextDate(Date date, int interval) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.set(Calendar.HOUR_OF_DAY, 0);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MILLISECOND, 0);

cal.add(Calendar.DAY_OF_MONTH, interval);

return cal.getTime();

}

/**

* 只格式化日期

*

* @param date

* @return

*/

public static String formatOnlyDate(Date date) {

SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_ONLY_DATE_I);

return sdf.format(date);

}

/**

* 格式化字符串 yyyy-MM-dd HH:mm

*

* @param date

* @return

*/

public static String formatDate(Date date, String format) {

if (date == null || StringUtils.isEmpty(format)) {

return null;

}

SimpleDateFormat sdf = new SimpleDateFormat(format);

return sdf.format(date);

}

/**

* 格式化字符串 MM月dd日 HH:mm

*

* @param date

* @return

*/

public static String formatTime(Date date) {

SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");

String dateStr = sdf.format(date);

if (dateStr.startsWith("0")) {

return dateStr.substring(1);

}

return dateStr;

}

/**

* 只格式化時(shí)間

*

* @param date

* @return

*/

public static String formatOnlyTime(Date date) {

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

return sdf.format(date);

}

/**

* 轉(zhuǎn)化時(shí)分

*

* @param date

* @return

*/

public static String formatHourAndMinute(Date date) {

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

return sdf.format(date);

}

/**

* 通過生日日期計(jì)算年齡(周歲算法):用當(dāng)年年份-生日年份,若若生日的月份和日數(shù) > 當(dāng)年的月份和日數(shù),則減1

*

* @param birDate

*? ? ? ? ? ? 生日日期

* @return int年齡

*/

public static int getAgeByBirDate(Date birDate) {

if (birDate == null) {

return 0;

}

int age = 0;

try {

if (birDate.after(new Date())) {

return 0;

}

Calendar now = Calendar.getInstance();

now.setTime(new Date());// 當(dāng)前時(shí)間

Calendar birth = Calendar.getInstance();

birth.setTime(birDate);// 生日日期

// 年齡為虛歲,用當(dāng)年年份-生日年份

age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);

birth.set(Calendar.YEAR, now.get(Calendar.YEAR));

now.set(Calendar.HOUR_OF_DAY, birth.get(Calendar.HOUR_OF_DAY));

now.set(Calendar.MINUTE, birth.get(Calendar.MINUTE));

now.set(Calendar.SECOND, birth.get(Calendar.SECOND));

now.set(Calendar.MILLISECOND, birth.get(Calendar.MILLISECOND));

if (birth.after(now)) {// 若生日的月份和日數(shù) > 當(dāng)年的月份和日數(shù),則減1

age--;

}

return age;

} catch (Exception e) {// 兼容性更強(qiáng),異常后返回?cái)?shù)據(jù)

return 0;

}

}

/**

* 通過年齡計(jì)算生日日期(周歲算法):年份減去年齡,默認(rèn)當(dāng)前的月份和日數(shù),為生日日期的月份和日數(shù)

*

* @param age

*? ? ? ? ? ? 年齡

* @return Date 生日日期

*/

public static Date getBirDateByAge(Integer age) {

if (age == null) {

return null;

}

Date birDate = new Date();

try {

Calendar now = Calendar.getInstance();

now.setTime(new Date());// 當(dāng)前時(shí)間

// 通過年齡計(jì)算生日日期,年份減去年齡,默認(rèn)當(dāng)前的月份和日數(shù) 為生日日期的月份和日數(shù)

now.add(Calendar.YEAR, 0 - age);

birDate = now.getTime();

return birDate;

} catch (Exception e) {// 兼容性更強(qiáng),異常后返回?cái)?shù)據(jù)

return null;

}

}

/**

* 獲取當(dāng)前時(shí)間

*

* @return

*/

public static Date getCurrentTime() {

TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));

Calendar cal = Calendar.getInstance();

Date date = cal.getTime();

return date;

}

/**

* 格式化日期和時(shí)間

*

* @param date

* @return

*/

public static String format(Date date) {

SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE_AND_TIME_I);

return sdf.format(date);

}

/**

* 根據(jù)格式格式化日期

*

* @param date

* @param pattern

* @return

* @throws ParseException

*/

public static Date parseDate(String date, String pattern) throws ParseException {

SimpleDateFormat format = new SimpleDateFormat(pattern);

return format.parse(date);

}

/**

* 獲得某天最小時(shí)間 2018-01-01 00:00:00

*

* @param date

* @return

*/

public static Date getMinTimeOfDay(Date date) {

LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),

ZoneId.systemDefault());

LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);

return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());

}

/**

* 獲得某天最大時(shí)間 2018-01-01 23:59:59

*

* @param date

* @return

*/

public static Date getMaxTimeOfDay(Date date) {

LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),

ZoneId.systemDefault());

LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);

return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

}

/**

* 獲取兩個(gè)時(shí)間間隔天數(shù)

*

* @param oldDate

* @param newDate

* @return

*/

public static Long getDateInterval(Date oldDate, Date newDate) {

if (oldDate == null || newDate == null) {

return null;

}

Calendar oldCal = Calendar.getInstance();

oldCal.setTime(oldDate);

LocalDate oldLocalDate = LocalDate.of(oldCal.get(Calendar.YEAR), oldCal.get(Calendar.MONTH) + 1,

oldCal.get(Calendar.DAY_OF_MONTH));

Calendar newCal = Calendar.getInstance();

newCal.setTime(newDate);

LocalDate newLocalDate = LocalDate.of(newCal.get(Calendar.YEAR), newCal.get(Calendar.MONTH) + 1,

newCal.get(Calendar.DAY_OF_MONTH));

return ChronoUnit.DAYS.between(oldLocalDate, newLocalDate);

}

/**

* 根據(jù)學(xué)生出生日期計(jì)算學(xué)齡

*

* @param birDate

* @return

*/

public static int getStudyAgeByBirDate(Date birDate) {

int age = 0;

try {

if (birDate.after(new Date())) {

return 0;

}

Calendar now = Calendar.getInstance();

now.setTime(new Date());// 當(dāng)前時(shí)間

// 把月份設(shè)置為9月1號(hào),8表示9月

now.set(Calendar.MONTH, 8);

now.set(Calendar.DAY_OF_MONTH, 1);

Calendar birth = Calendar.getInstance();

birth.setTime(birDate);// 生日日期

// 年齡為虛歲,用當(dāng)年年份-生日年份

age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);

birth.set(Calendar.YEAR, now.get(Calendar.YEAR));

now.set(Calendar.HOUR_OF_DAY, birth.get(Calendar.HOUR_OF_DAY));

now.set(Calendar.MINUTE, birth.get(Calendar.MINUTE));

now.set(Calendar.SECOND, birth.get(Calendar.SECOND));

now.set(Calendar.MILLISECOND, birth.get(Calendar.MILLISECOND));

if (birth.after(now)) {// 若生日的月份和日數(shù) > 當(dāng)年的月份和日數(shù),則減1

age--;

}

return age;

} catch (Exception e) {// 兼容性更強(qiáng),異常后返回?cái)?shù)據(jù)

return 0;

}

}

/**

? ? * 獲得date所在周的周一日期

? ? *

? ? * @return

? ? */

? ? public static Date getThisMondayDate(Date date) {

? ? ? ? Calendar calendar = Calendar.getInstance();

? ? ? ? calendar.setTime(date);

? ? ? ? // 國(guó)外的習(xí)慣是周日是一周的第一天 如果今天是星期天 那么 國(guó)內(nèi) 的定義 這周的星期一是六天前 而國(guó)外是第二天

? ? ? ? int days = 0;

? ? ? ? if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {

? ? ? ? ? ? days = -6;

? ? ? ? } else {

? ? ? ? ? ? days = Calendar.MONDAY - calendar.get(Calendar.DAY_OF_WEEK);

? ? ? ? }

? ? ? ? calendar.add(Calendar.DATE, days);

? ? ? ? calendar.set(Calendar.HOUR_OF_DAY, 0);

? ? ? ? calendar.set(Calendar.MINUTE, 0);

? ? ? ? calendar.set(Calendar.SECOND, 0);

? ? ? ? calendar.set(Calendar.MILLISECOND, 0);

? ? ? ? return calendar.getTime();

? ? }

? ? /**

? ? * 返回指定天數(shù)的日期

? ? *

? ? * @param date

? ? * @param day

? ? * @return

? ? */

? ? public static Date getExpireDate(Date date, int day) {

? ? ? ? Calendar cal = Calendar.getInstance();

? ? ? ? cal.setTime(date);

? ? ? ? cal.add(Calendar.DAY_OF_MONTH, day);

? ? ? ? return cal.getTime();

? ? }

? ? /**

? ? * <p>Title: getExpireHour</p>

? ? * <p>Description: 返回指定日期多少小時(shí)后的時(shí)間</p>

? ? *

? ? * @param date

? ? * @param hour

? ? * @return

? ? * @author yql

? ? */

? ? public static Date getExpireHour(Date date, int hour) {

? ? ? ? Calendar cal = Calendar.getInstance();

? ? ? ? cal.setTime(date);

? ? ? ? cal.add(Calendar.HOUR_OF_DAY, hour);

? ? ? ? return cal.getTime();

? ? }

? ? /**

? ? * 日期 時(shí)間拼成 date類型

? ? * @param date yyyy-MM-dd

? ? * @param time HH:mm

? ? * @return

? ? */

? ? public static Date toDate(Date date, Date time) {

? ? ? ? String dateStr = formatDate(date, 0);

? ? ? ? String timeStr = formatDate(time, 20);

? ? ? ? String dateTimeStr = dateStr + " " + timeStr;

? ? ? ? return toDate(dateTimeStr,21);

? ? }

? ? /**

? ? * 根據(jù)指定參數(shù)kind,獲取指定類型的Date日期(年月日)

? ? * @param kind 指定參數(shù)

? ? * @return Date 指定類型的Date

? ? */

? ? public static Date getFormatDate(Date date, int kind) {

? ? ? ? String currentDateStr = formatDate( date , kind);

? ? ? ? return toDate(currentDateStr, kind);

? ? }

? ? /**

? ? * 根據(jù)kind輸出string格式

? ? *

? ? * @param date

? ? * @param kind

? ? * @return

? ? */

? ? public static String formatDate(Date date, int kind) {

? ? ? ? SimpleDateFormat sdf = new SimpleDateFormat(getDateFormat(kind));

? ? ? ? return sdf.format(date);

? ? }

? ? public static String formatCurrentDate(int kind) {

? ? ? ? SimpleDateFormat sdf = new SimpleDateFormat(getDateFormat(kind));

? ? ? ? return sdf.format(new Date());

? ? }

? ? public static Date toDate(String dateText, int kind) {

? ? ? ? String format = getDateFormat(kind);

? ? ? ? if (dateText == null) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? DateFormat df = null;

? ? ? ? try {

? ? ? ? ? ? if (format == null) {

? ? ? ? ? ? ? ? df = new SimpleDateFormat();

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? df = new SimpleDateFormat(format);

? ? ? ? ? ? }

? ? ? ? ? ? df.setLenient(false);

? ? ? ? ? ? return df.parse(dateText);

? ? ? ? } catch (ParseException e) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? }

? ? private static String getDateFormat(int kind) {

? ? ? ? String[] format = {"yyyy-MM-dd", // 0

? ? ? ? ? ? ? ? "yyyy-MM-dd HH:mm:ss", // 1

? ? ? ? ? ? ? ? "yyyy",// 2

? ? ? ? ? ? ? ? "M",// 3

? ? ? ? ? ? ? ? "dd", // 4

? ? ? ? ? ? ? ? "yyyy年M月d日H點(diǎn)m分", // 5

? ? ? ? ? ? ? ? "yyyy年M月d日", // 6

? ? ? ? ? ? ? ? "H點(diǎn)m分", // 7

? ? ? ? ? ? ? ? "yyyy/MM/dd HH:mm", // 8

? ? ? ? ? ? ? ? "HH",// 9

? ? ? ? ? ? ? ? "mm",// 10

? ? ? ? ? ? ? ? "yyyyMMdd", // 11

? ? ? ? ? ? ? ? "yyyyMMddHHmmss", // 12

? ? ? ? ? ? ? ? "yyyy-MM-dd 23:59:59", // 13

? ? ? ? ? ? ? ? "HH:mm:ss", // 14

? ? ? ? ? ? ? ? "yyyy/MM/dd HH:mm:ss", // 15

? ? ? ? ? ? ? ? "yyyy/MM/dd HH:mm",//16

? ? ? ? ? ? ? ? "HHmmss",//17,

? ? ? ? ? ? ? ? "HH:mm:ss", //18

? ? ? ? ? ? ? ? "mmss", //19

? ? ? ? ? ? ? ? "HH:mm", //20

? ? ? ? ? ? ? ? "yyyy-MM-dd HH:mm" //21

? ? ? ? };

? ? ? ? return format[kind];

? ? }

? ? /**

? ? * 計(jì)算兩個(gè)日期的秒數(shù)之差

? ? *

? ? * @param oldDate

? ? * @param newDate

? ? * @return

? ? */

? ? public static long secondsBetween(Date oldDate, Date newDate) {

? ? ? ? long between = (newDate.getTime() / 1000 - oldDate.getTime() / 1000);//除以1000是為了轉(zhuǎn)換成秒

? ? ? ? return between;

? ? }

? ? /**

? ? * 計(jì)算傳入時(shí)間距離24點(diǎn)剩余秒數(shù)

? ? * @param currentDate

? ? * @return

? ? */

? ? public static Integer getRemainSecondsOneDay(Date currentDate) {

? ? ? ? LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),

? ? ? ? ? ? ? ? ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)

? ? ? ? ? ? ? ? .withSecond(0).withNano(0);

? ? ? ? LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),

? ? ? ? ? ? ? ? ZoneId.systemDefault());

? ? ? ? long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);

? ? ? ? return (int) seconds;

? ? }

? ? /**

? ? *返回指定月數(shù)的日期

? ? * @param date

? ? * @param month

? ? * @author? guos

? ? * @date 2019/4/13 16:26

? ? * @return

? ? **/

? ? public static Date getExpireMonth(Date date, int month) {

? ? ? ? Calendar cal = Calendar.getInstance();

? ? ? ? cal.setTime(date);

? ? ? ? cal.add(Calendar.MONTH, month);

? ? ? ? return cal.getTime();

? ? }

? ? /**

? ? *校驗(yàn)日期是否合法

? ? * @param startDate 開始日期

? ? * @param endDate 結(jié)束日期

? ? * @param interval 日期間隔月份 :-1,導(dǎo)出所有

? ? * @author? guos

? ? * @date 2019/4/13 16:26

? ? * @return

? ? **/

? ? public static void checkDate(Date startDate, Date endDate, int interval) {

? ? ? ? if (interval == -1) {

? ? ? ? ? ? return;

? ? ? ? }

? ? ? ? if (interval < 0) {

? ? ? ? ? ? throw new BizException("日期間隔不能小于0");

? ? ? ? }

? ? ? ? if (startDate.after(endDate)) {

? ? ? ? ? ? throw new BizException("開始日期不能晚于結(jié)束日期");

? ? ? ? }

? ? ? ? if (getExpireMonth(startDate, interval).before(endDate)) {

? ? ? ? ? ? throw new BizException("因數(shù)據(jù)量關(guān)系,僅能導(dǎo)出" + interval + "個(gè)月的數(shù)據(jù)");

? ? ? ? }

? ? }

}

```

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容