常用的時間格式化工具整理

···

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;

}

/**

* 只格式化時間

*

* @param date

* @return

*/

public static String formatOnlyTime(Date date) {

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

return sdf.format(date);

}

/**

* 轉(zhuǎn)化時分

*

* @param date

* @return

*/

public static String formatHourAndMinute(Date date) {

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

return sdf.format(date);

}

/**

* 通過生日日期計算年齡(周歲算法):用當年年份-生日年份,若若生日的月份和日數(shù) > 當年的月份和日數(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());// 當前時間

Calendar birth = Calendar.getInstance();

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

// 年齡為虛歲蹋盆,用當年年份-生日年份

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ù) > 當年的月份和日數(shù)迈勋,則減1

age--;

}

return age;

} catch (Exception e) {// 兼容性更強,異常后返回數(shù)據(jù)

return 0;

}

}

/**

* 通過年齡計算生日日期(周歲算法):年份減去年齡伐脖,默認當前的月份和日數(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());// 當前時間

// 通過年齡計算生日日期拍皮,年份減去年齡隧膏,默認當前的月份和日數(shù) 為生日日期的月份和日數(shù)

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

birDate = now.getTime();

return birDate;

} catch (Exception e) {// 兼容性更強,異常后返回數(shù)據(jù)

return null;

}

}

/**

* 獲取當前時間

*

* @return

*/

public static Date getCurrentTime() {

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

Calendar cal = Calendar.getInstance();

Date date = cal.getTime();

return date;

}

/**

* 格式化日期和時間

*

* @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);

}

/**

* 獲得某天最小時間 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());

}

/**

* 獲得某天最大時間 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());

}

/**

* 獲取兩個時間間隔天數(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ù)學生出生日期計算學齡

*

* @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());// 當前時間

// 把月份設置為9月1號奠宜,8表示9月

now.set(Calendar.MONTH, 8);

now.set(Calendar.DAY_OF_MONTH, 1);

Calendar birth = Calendar.getInstance();

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

// 年齡為虛歲包颁,用當年年份-生日年份

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ù) > 當年的月份和日數(shù)瞻想,則減1

age--;

}

return age;

} catch (Exception e) {// 兼容性更強,異常后返回數(shù)據(jù)

return 0;

}

}

/**

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

? ? *

? ? * @return

? ? */

? ? public static Date getThisMondayDate(Date date) {

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

? ? ? ? calendar.setTime(date);

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

? ? ? ? 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: 返回指定日期多少小時后的時間</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();

? ? }

? ? /**

? ? * 日期 時間拼成 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點m分", // 5

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

? ? ? ? ? ? ? ? "H點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];

? ? }

? ? /**

? ? * 計算兩個日期的秒數(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;

? ? }

? ? /**

? ? * 計算傳入時間距離24點剩余秒數(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();

? ? }

? ? /**

? ? *校驗日期是否合法

? ? * @param startDate 開始日期

? ? * @param endDate 結束日期

? ? * @param interval 日期間隔月份 :-1,導出所有

? ? * @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("開始日期不能晚于結束日期");

? ? ? ? }

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

? ? ? ? ? ? throw new BizException("因數(shù)據(jù)量關系娩嚼,僅能導出" + interval + "個月的數(shù)據(jù)");

? ? ? ? }

? ? }

}

```

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蘑险,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子岳悟,更是在濱河造成了極大的恐慌漠其,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件竿音,死亡現(xiàn)場離奇詭異和屎,居然都是意外死亡,警方通過查閱死者的電腦和手機春瞬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進店門柴信,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宽气,你說我怎么就攤上這事随常。” “怎么了萄涯?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵绪氛,是天一觀的道長。 經(jīng)常有香客問我涝影,道長枣察,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任燃逻,我火速辦了婚禮序目,結果婚禮上,老公的妹妹穿的比我還像新娘伯襟。我一直安慰自己猿涨,他們只是感情好,可當我...
    茶點故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布姆怪。 她就那樣靜靜地躺著叛赚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪稽揭。 梳的紋絲不亂的頭發(fā)上俺附,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天,我揣著相機與錄音淀衣,去河邊找鬼昙读。 笑死,一個胖子當著我的面吹牛膨桥,可吹牛的內(nèi)容都是我干的蛮浑。 我是一名探鬼主播唠叛,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼沮稚!你這毒婦竟也來了艺沼?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后丰辣,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡挽荡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了即供。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片定拟。...
    茶點故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖逗嫡,靈堂內(nèi)的尸體忽然破棺而出青自,到底是詐尸還是另有隱情,我是刑警寧澤驱证,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布延窜,位于F島的核電站,受9級特大地震影響抹锄,放射性物質(zhì)發(fā)生泄漏逆瑞。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一祈远、第九天 我趴在偏房一處隱蔽的房頂上張望呆万。 院中可真熱鬧商源,春花似錦车份、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至庄吼,卻和暖如春缎除,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背总寻。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工器罐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人渐行。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓轰坊,卻偏偏與公主長得像铸董,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子肴沫,可洞房花燭夜當晚...
    茶點故事閱讀 44,974評論 2 355

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