溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java中怎么實(shí)現(xiàn)一個(gè)日期時(shí)間轉(zhuǎn)換工具類

發(fā)布時(shí)間:2021-07-22 16:07:26 來源:億速云 閱讀:118 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)java中怎么實(shí)現(xiàn)一個(gè)日期時(shí)間轉(zhuǎn)換工具類,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

具體如下:

package com.incar.base.util;import com.incar.base.exception.BaseRuntimeException;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.time.*;import java.time.temporal.ChronoField;import java.time.temporal.ChronoUnit;import java.time.temporal.WeekFields;import java.util.*;/** * Created by Administrator on 2017/4/11. */public class DateUtil { public final static String DATE_FORMAT_DAY = "yyyy-MM-dd"; public final static String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss"; private final static int[] DATE_UNIT_ARR = new int[]{Calendar.MILLISECOND, Calendar.SECOND, Calendar.MINUTE, Calendar.HOUR_OF_DAY,   Calendar.DATE, Calendar.MONTH, Calendar.YEAR}; public static Calendar calendar = null; public static DateFormat dateFormat = null; public static Date date = null; /**  * 將日期轉(zhuǎn)為 字符串  * @param date  * @param format  * @return  */ public static String dateToString(Date date, String format) {  if (date == null) {   return null;  }  return new SimpleDateFormat(format).format(date); } /**  * 將日期轉(zhuǎn)換為 字符串(轉(zhuǎn)換的時(shí)間按照當(dāng)前登錄用戶的時(shí)區(qū))  *  * @param date  * @param format  * @param timeZone  * @return  */ public static String dateToString(Date date, String format, String timeZone) {  if (date == null) {   return null;  }  //1、格式化日期  return getTimeZoneSimpleDateFormat(format, timeZone).format(date); } /**  * 獲取當(dāng)前登錄用戶的 日期格式化對(duì)象  *  * @param timeZone  * @param format  * @return  */ private static SimpleDateFormat getTimeZoneSimpleDateFormat(String format, String timeZone) {  //1、獲取對(duì)應(yīng)時(shí)區(qū)的格式化器  SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);  simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));  return simpleDateFormat; } /**  *將字符串轉(zhuǎn)為日期(轉(zhuǎn)換的時(shí)間按照當(dāng)前登錄用戶的時(shí)區(qū))  * @param dateStr  * @param format  * @return  */ public static Date stringToDate(String dateStr, String format, String timeZone) {  if (dateStr == null || format == null) {   return null;  }  try {   return getTimeZoneSimpleDateFormat(format, timeZone).parse(dateStr);  } catch (ParseException e) {   throw BaseRuntimeException.getException(e);  } } /**  *將字符串轉(zhuǎn)為日期  * @param dateStr  * @param format  * @return  */ public static Date stringToDate_CTT(String dateStr, String format) {  if (dateStr == null || format == null) {   return null;  }  try {   return getTimeZoneSimpleDateFormat(format, "CTT").parse(dateStr);  } catch (ParseException e) {   throw BaseRuntimeException.getException(e);  } } /**  * 獲取最近在當(dāng)前日期之前的最后一個(gè)日期單位  *  * @param date  * @param calendarUnit 只支持 DateUtil.DATE_UNIT_ARR  * @return  */ public static Date getFloorDate(Date date, int calendarUnit) {  if (date == null) {   return null;  }  Calendar calendar = Calendar.getInstance();  calendar.setTime(date);  for (int i = 0; i <= DATE_UNIT_ARR.length - 1; i++) {   if (DATE_UNIT_ARR[i] > calendarUnit) {    if (Calendar.DATE == DATE_UNIT_ARR[i]) {     calendar.set(DATE_UNIT_ARR[i], 1);    } else {     calendar.set(DATE_UNIT_ARR[i], 0);    }   }   if (DATE_UNIT_ARR[i] == calendarUnit) {    break;   }  }  return calendar.getTime(); } /**  * 獲取最近在當(dāng)前日期之后的第一個(gè)日期單位  *  * @param date  * @param calendarUnit 只支持 DateUtil.DATE_UNIT_ARR  * @return  */ public static Date getCeilDate(Date date, int calendarUnit) {  if (date == null) {   return null;  }  Calendar calendar = Calendar.getInstance();  calendar.setTime(date);  for (int i = 0; i <= DATE_UNIT_ARR.length - 1; i++) {   if (DATE_UNIT_ARR[i] > calendarUnit) {    if (Calendar.DATE == DATE_UNIT_ARR[i]) {     calendar.set(DATE_UNIT_ARR[i], 1);    } else {     calendar.set(DATE_UNIT_ARR[i], 0);    }   }   if (DATE_UNIT_ARR[i] == calendarUnit) {    calendar.add(DATE_UNIT_ARR[i], 1);    break;   }  }  return calendar.getTime(); } /**  * 將開始時(shí)間、結(jié)束時(shí)間 根據(jù)日期單位劃分成 時(shí)間段  *  *  * @param startDate  * @param endDate  * @param calendarUnit Calendar.MONTH,Calendar.DATE  * @param dateNum  指定的單位日期數(shù)量  * @return 每一個(gè)數(shù)組第一個(gè)為開始時(shí)間,第二個(gè)為結(jié)束時(shí)間; 第一個(gè)元素結(jié)束時(shí)間總是等于第二元素開始時(shí)間  */ public static List<Date[]> splitDate(Date startDate, Date endDate, int calendarUnit, int dateNum) {  List<Date[]> returnList = new ArrayList<>();  if (startDate.getTime() > endDate.getTime()) {   return null;  }  Calendar c1 = Calendar.getInstance();  Calendar c2 = Calendar.getInstance();  c1.setTime(startDate);  c2.setTime(endDate);  Calendar curC1 = Calendar.getInstance();  Calendar curC2 = null;  curC1.setTime(startDate);  while (curC2 == null || curC2.before(c2)) {   if (curC2 == null) {    curC2 = Calendar.getInstance();    curC2.setTime(startDate);    curC2.add(calendarUnit, dateNum);   } else {    curC1.add(calendarUnit, dateNum);    curC2.add(calendarUnit, dateNum);   }   returnList.add(new Date[]{curC1.getTime(), curC2.getTime()});  }  //設(shè)置最后一個(gè)區(qū)間的截至日期為endDate  returnList.get(returnList.size() - 1)[1] = endDate;  return returnList; } /**  * 獲取開始時(shí)間結(jié)束時(shí)間按照 日期單位 形成多個(gè)日期區(qū)間  * 分割出來的時(shí)間區(qū)間以  * 第一個(gè)區(qū)間開始時(shí)間為傳入開始時(shí)間  * 最后一個(gè)區(qū)間結(jié)束時(shí)間為傳入結(jié)束時(shí)間  * @param startDate  * @param endDate  * @param unit 1:代表按日;2:代表按周;3:代表按月  * @return  */ public static List<Date[]> rangeDate(Date startDate, Date endDate, int unit){  List<Date[]> returnList=new ArrayList<>();  LocalDateTime ldt1= LocalDateTime.ofInstant(startDate.toInstant(),ZoneId.of("+8"));  LocalDateTime ldt2= LocalDateTime.ofInstant(endDate.toInstant(),ZoneId.of("+8"));  switch (unit){   case 1:{    LocalDateTime start= ldt1.with(ChronoField.SECOND_OF_DAY,0);    LocalDateTime end= ldt1.with(ChronoField.SECOND_OF_DAY, ChronoUnit.DAYS.getDuration().getSeconds()-1);    while(true){     returnList.add(new Date[]{Date.from(start.toInstant(ZoneOffset.of("+8"))),Date.from(end.toInstant(ZoneOffset.of("+8")))});     if(!ldt2.isBefore(start)&&!ldt2.isAfter(end)){      break;     }else{      start=start.plusDays(1);      end=end.plusDays(1);     }    }    break;   }   case 2:{    int dayOfWeek=ldt1.get(ChronoField.DAY_OF_WEEK);    LocalDateTime start= ldt1.plusDays(1-dayOfWeek).with(ChronoField.SECOND_OF_DAY,0);    LocalDateTime end= ldt1.plusDays(7-dayOfWeek).with(ChronoField.SECOND_OF_DAY, ChronoUnit.DAYS.getDuration().getSeconds()-1);    while(true){     returnList.add(new Date[]{Date.from(start.toInstant(ZoneOffset.of("+8"))),Date.from(end.toInstant(ZoneOffset.of("+8")))});     if(!ldt2.isBefore(start)&&!ldt2.isAfter(end)){      break;     }else{      start=start.plusWeeks(1);      end=end.plusWeeks(1);     }    }    if(returnList.size()>0){     Date[] firstEle=returnList.get(0);     Date[] lastEle=returnList.get(returnList.size()-1);     firstEle[0]=Date.from(ldt1.with(ChronoField.SECOND_OF_DAY,0).toInstant(ZoneOffset.of("+8")));     lastEle[1]=Date.from(ldt2.with(ChronoField.SECOND_OF_DAY,0).toInstant(ZoneOffset.of("+8")));    }    break;   }   case 3:{    LocalDateTime temp=ldt1;    while(true) {     int dayOfMonth = temp.get(ChronoField.DAY_OF_MONTH);     int max = temp.getMonth().maxLength();     LocalDateTime start = temp.plusDays(1 - dayOfMonth).with(ChronoField.SECOND_OF_DAY, 0);     LocalDateTime end = temp.plusDays(max - dayOfMonth).with(ChronoField.SECOND_OF_DAY, ChronoUnit.DAYS.getDuration().getSeconds() - 1);     returnList.add(new Date[]{Date.from(start.toInstant(ZoneOffset.of("+8"))),Date.from(end.toInstant(ZoneOffset.of("+8")))});     if(!ldt2.isBefore(start)&&!ldt2.isAfter(end)){      break;     }else{      temp=temp.plusMonths(1);     }    }    if(returnList.size()>0){     Date[] firstEle=returnList.get(0);     Date[] lastEle=returnList.get(returnList.size()-1);     firstEle[0]=Date.from(ldt1.with(ChronoField.SECOND_OF_DAY,0).toInstant(ZoneOffset.of("+8")));     lastEle[1]=Date.from(ldt2.with(ChronoField.SECOND_OF_DAY,0).toInstant(ZoneOffset.of("+8")));    }    break;   }  }  return returnList; } /**  * 計(jì)算兩個(gè)時(shí)間相差多少日期單位(不足一個(gè)日期單位的的按一個(gè)日期單位算)  *  * @param d1 開始時(shí)間  * @param d2 結(jié)束時(shí)間  * @return 相差日期單位數(shù)  */ public static int getDiff(Date d1, Date d2, int calendarUnit) {  double diff;  switch (calendarUnit) {   case Calendar.DATE: {    diff = 1000 * 60 * 60 * 24;    break;   }   case Calendar.HOUR_OF_DAY: {    diff = 1000 * 60 * 60;    break;   }   case Calendar.MINUTE: {    diff = 1000 * 60;    break;   }   case Calendar.SECOND: {    diff = 1000;    break;   }   default: {    throw BaseRuntimeException.getException("[DateUtil.getDiff],Calendar Unit Not Support!");   }  }  Long begin = d1.getTime();  Long end = d2.getTime();  Double res = (end - begin) / diff;  return (int) Math.ceil(res); } /**  * 會(huì)改變參數(shù)值  * 格式化日期參數(shù)開始日期和結(jié)束日期  * 格式規(guī)則為:  * 開始日期去掉時(shí)分秒  * 結(jié)束日期設(shè)置為當(dāng)天 23:59:59  *  * @param startDate  * @param endDate  */ public static void formatDateParam(Date startDate, Date endDate) {  if (startDate != null) {   startDate.setTime(getFloorDate(startDate, Calendar.DATE).getTime());  }  if (endDate != null) {   Date tempDate = getCeilDate(endDate, Calendar.DATE);   Calendar endC = Calendar.getInstance();   endC.setTime(tempDate);   endC.add(Calendar.SECOND, -1);   endDate.setTime(endC.getTimeInMillis());  } } /**  * 獲取一個(gè)日期的數(shù)字表示形式  * 例如:  * 2018-3-12 15:13:12 888 表示成 20180312151312888  *  * @param date  * @param calendarUnit 最小的日期單位  * @return  */ public static Long getDateNum(Date date, int calendarUnit) {  if (date == null) {   return null;  }  StringBuffer sb = new StringBuffer();  Calendar c = Calendar.getInstance();  c.setTime(date);  if (calendarUnit >= Calendar.YEAR) {   sb.append(c.get(Calendar.YEAR));  }  if (calendarUnit >= Calendar.MONTH) {   sb.append(FormatUtil.formatToString(c.get(Calendar.MONTH) + 1, "00"));  }  if (calendarUnit >= Calendar.DATE) {   sb.append(FormatUtil.formatToString(c.get(Calendar.DATE), "00"));  }  if (calendarUnit >= Calendar.HOUR_OF_DAY) {   sb.append(FormatUtil.formatToString(c.get(Calendar.HOUR_OF_DAY), "00"));  }  if (calendarUnit >= Calendar.MINUTE) {   sb.append(FormatUtil.formatToString(c.get(Calendar.MINUTE), "00"));  }  if (calendarUnit >= Calendar.SECOND) {   sb.append(FormatUtil.formatToString(c.get(Calendar.SECOND), "00"));  }  if (calendarUnit >= Calendar.MILLISECOND) {   sb.append(FormatUtil.formatToString(c.get(Calendar.MILLISECOND), "000"));  }  return Long.parseLong(sb.toString()); } /**  * 判斷兩個(gè)日期是否相等  *  * @param d1  * @param d2  * @param calendarUnit 對(duì)比的最小日期單位  * @return  */ public static boolean isEqual(Date d1, Date d2, int calendarUnit) {  Calendar c1 = Calendar.getInstance();  Calendar c2 = Calendar.getInstance();  c1.setTime(d1);  c2.setTime(d2);  for (int i = DATE_UNIT_ARR.length - 1; i >= 0; i--) {   if (calendarUnit >= DATE_UNIT_ARR[i]) {    int v1 = c1.get(DATE_UNIT_ARR[i]);    int v2 = c2.get(DATE_UNIT_ARR[i]);    if (v1 != v2) {     return false;    }   } else {    break;   }  }  return true; } /**  * 獲取當(dāng)天初始時(shí)間  *  * @param date 時(shí)間  * @return 初始時(shí)間 (yyyy-MM-dd 00:00:00)  */ public static Date getInitialTime(Date date) {  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");  String dateStr = dateFormat.format(date);  try {   return dateFormat.parse(dateStr);  } catch (ParseException e) {   e.printStackTrace();  }  return null; } /**  * 獲取當(dāng)天最后時(shí)間  *  * @param date 時(shí)間  * @return 最后時(shí)間 (yyyy-MM-dd 23:59:59)  */ public static Date getTerminalTime(Date date) {  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  String dateStr = dateFormat.format(date);  dateStr = dateStr + " 23:59:59";  dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  try {   return dateFormat.parse(dateStr);  } catch (ParseException e) {   e.printStackTrace();  }  return null; } public static String date2Str(Date date) {  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  return dateFormat.format(date); } /**  * 計(jì)算兩個(gè)時(shí)間間隔多少秒  *  * @param startDate  * @param endDate  * @return  */ public static Long intervalTime(Date startDate, Date endDate) {  long a = endDate.getTime();  long b = startDate.getTime();  Long c = ((a - b) / 1000);  return c; } /**  * 檢測(cè)一個(gè)日期是否在 小時(shí)之內(nèi),支持跨天的小時(shí)  *  * @param time  * @param startDate  * @param endDate  * @return  */ public static boolean checkDateIn(Date time, Date startDate, Date endDate) {  if (startDate == null || endDate == null || time == null) {   return true;  }  return time.before(endDate) && time.after(startDate); } /**  * 檢測(cè)一個(gè)日期是否在 時(shí)分秒 之內(nèi),支持跨天的小時(shí)  *  * @param time  * @param startHms  * @param endHms  * @return  */ public static boolean checkHmsIn(Date time, String startHms, String endHms) {  if (startHms == null || endHms == null || time == null) {   return true;  }  LocalTime startTime = LocalTime.of(    Integer.valueOf(startHms.substring(0, 2)),    Integer.valueOf(startHms.substring(2, 4)),    Integer.valueOf(startHms.substring(4, 6))  );  LocalTime endTime = LocalTime.of(    Integer.valueOf(endHms.substring(0, 2)),    Integer.valueOf(endHms.substring(2, 4)),    Integer.valueOf(endHms.substring(4, 6))  );  LocalTime curTime = LocalDateTime.ofInstant(time.toInstant(), ZoneId.of("+8")).toLocalTime();  if (endTime.isAfter(startTime)) {   return startTime.isBefore(curTime) && endTime.isAfter(curTime);  } else {   return (startTime.isBefore(curTime) && LocalTime.MAX.isAfter(curTime)) || (LocalTime.MIN.isBefore(curTime) && endTime.isAfter(curTime));  } } /**  * 功能描述:格式化日期  *  * @param dateStr 字符型日期:YYYY/MM/DD 格式  * @return Date 日期  */ public static Date parseDate(String dateStr) {  return parseDate(dateStr, "yyyy-MM-dd"); } /**  * 功能描述:格式化日期  *  * @param dateStr 字符型日期  * @param format 格式  * @return Date 日期  */ public static Date parseDate(String dateStr, String format) {  try {   dateFormat = new SimpleDateFormat(format);   String dt = dateStr.replaceAll("-", "/");   if ((!dt.equals("")) && (dt.length() < format.length())) {    dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]",      "0");   }   date = (Date) dateFormat.parse(dt);  } catch (Exception e) {   return null;  }  return date; } public static Date stringParseDate(String date) throws ParseException {  //獲取的值為"19570323"  //1、定義轉(zhuǎn)換格式  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMdd");  //2、調(diào)用formatter2.parse(),將"19570323"轉(zhuǎn)化為date類型 輸出為:Sat Mar 23 00:00:00 GMT+08:00 1957  Date parseDate = formatter2.parse(date);  return parseDate; }}

以上就是java中怎么實(shí)現(xiàn)一個(gè)日期時(shí)間轉(zhuǎn)換工具類,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI