栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现的日期时间转换工具类完整示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现的日期时间转换工具类完整示例

本文实例讲述了java实现的日期时间转换工具类。分享给大家供大家参考,具体如下:

最基础的东西,总结一下,下次用的时候就方便一些了。废话不多说,直接贴代码:

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.*;

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;
 
 public static String dateToString(Date date, String format) {
  if (date == null) {
   return null;
  }
  return new SimpleDateFormat(format).format(date);
 }
 
 public static String dateToString(Date date, String format, String timeZone) {
  if (date == null) {
   return null;
  }
  //1、格式化日期
  return getTimeZoneSimpleDateFormat(format, timeZone).format(date);
 }
 
 private static SimpleDateFormat getTimeZoneSimpleDateFormat(String format, String timeZone) {
  //1、获取对应时区的格式化器
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
  simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
  return simpleDateFormat;
 }
 
 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);
  }
 }
 
 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);
  }
 }
 
 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();
 }
 
 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();
 }
 
 public static List splitDate(Date startDate, Date endDate, int calendarUnit, int dateNum) {
  List 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()});
  }
  //设置最后一个区间的截至日期为endDate
  returnList.get(returnList.size() - 1)[1] = endDate;
  return returnList;
 }
 
 public static List rangeDate(Date startDate, Date endDate, int unit){
  List 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;
 }
 
 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);
 }
 
 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());
  }
 }
 
 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());
 }
 
 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;
 }
 
 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;
 }
 
 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);
 }
 
 public static Long intervalTime(Date startDate, Date endDate) {
  long a = endDate.getTime();
  long b = startDate.getTime();
  Long c = ((a - b) / 1000);
  return c;
 }
 
 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);
 }
 
 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));
  }
 }
 
 public static Date parseDate(String dateStr) {
  return parseDate(dateStr, "yyyy-MM-dd");
 }
 
 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、定义转换格式
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMdd");
  //2、调用formatter2.parse(),将"19570323"转化为date类型 输出为:Sat Mar 23 00:00:00 GMT+08:00 1957
  Date parseDate = formatter2.parse(date);
  return parseDate;
 }
}

PS:这里再为大家推荐几款关于日期与时间计算的在线工具供大家参考使用:

在线日期/天数计算器:
http://tools.jb51.net/jisuanqi/date_jisuanqi

在线万年历日历:
http://tools.jb51.net/bianmin/wannianli

在线阴历/阳历转换工具:
http://tools.jb51.net/bianmin/yinli2yangli

Unix时间戳(timestamp)转换工具:
http://tools.jb51.net/code/unixtime

更多关于java相关内容感兴趣的读者可查看本站专题:《java日期与时间操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/136567.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号