常用工具类---日期时间工具

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
应用实时监控服务-可观测链路OpenTelemetry版,每月50GB免费额度
MSE Nacos/ZooKeeper 企业版试用,1600元额度,限量50份
简介: 诸多时间的获取及计算,以及一些时间类型的转换!!!都是非常实用的哦~~~

引包参考

import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Random;

分钟转小时

public static String minuteToHour(long minutes) {
    long hours = (long) Math.floor(minutes / 60);
    long minute = minutes % 60;
    if (0 == minute) {
        return hours + "小时";
    } else if (hours > 0) {
        return hours + "小时" + minute + "分钟";
    } else {
        return minute + "分钟";
    }
}

获取当天开始/结束时间

public static Date getDayBegin(){
    // 开始
    Calendar cal=Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);//0点
    cal.set(Calendar.MINUTE, 0);//0分
    cal.set(Calendar.SECOND, 0);//0秒
    cal.set(Calendar.MILLISECOND, 0);//0毫秒
    return cal.getTime();
    
    // 结束
    Calendar cal=Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 23);//23点
    cal.set(Calendar.MINUTE, 59);//59分
    cal.set(Calendar.SECOND, 59);//59秒
    return cal.getTime();
}

获取昨天开始/结束时间

public static Date getBeginDayOfYesterday(){
    // 开始
    Calendar cal=Calendar.getInstance();
    cal.setTime(getDayBegin());//当天开始时间
    cal.add(Calendar.DAY_OF_MONTH, -1);//当天月份天数减1
    return cal.getTime();
    
    // 结束
    Calendar cal=Calendar.getInstance();
    cal.setTime(getDayEnd());//当天结束时间
    cal.add(Calendar.DAY_OF_MONTH, -1);//当天月份天数减1
    return cal.getTime();
}

获取明天开始/结束时间

public static Date getBeginDayOfTomorrow(){
    // 开始
    Calendar cal=Calendar.getInstance();
    cal.setTime(getDayBegin());//当天开始时间
    cal.add(Calendar.DAY_OF_MONTH, 1);//当天月份天数加1
    return cal.getTime();
    
    // 结束
    Calendar cal=Calendar.getInstance();
    cal.setTime(getDayEnd());//当天结束时间
    cal.add(Calendar.DAY_OF_MONTH, 1);//当天月份天数加1
    return cal.getTime();
}

获取某个日期的开始/结束时间


public static Timestamp getDayStartTime(Date d) {
    // 开始
    Calendar calendar=Calendar.getInstance();
    if(null!=d){
        calendar.setTime(d);
    }
    calendar.set(calendar.get(Calendar.YEAR),
                 calendar.get(Calendar.MONTH),
                 calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return new Timestamp(calendar.getTimeInMillis());
    
    // 结束
     Calendar calendar=Calendar.getInstance();
    if(null!=d){
        calendar.setTime(d);
    }
    calendar.set(calendar.get(Calendar.YEAR),
                 calendar.get(Calendar.MONTH),
                 calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return new Timestamp(calendar.getTimeInMillis());
}

获取本周的开始/结束时间

public static Date getBeginDayOfWeek(){
    // 开始
    Date date=new Date();
    if(date==null){
        return null;
    }
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    int dayOfWeek=cal.get(Calendar.DAY_OF_WEEK);
    if(dayOfWeek==1){
        dayOfWeek+=7;
    }
    cal.add(Calendar.DATE, 2-dayOfWeek);
    return getDayStartTime(cal.getTime());
    
    // 结束
    Calendar cal=Calendar.getInstance();
    cal.setTime(getBeginDayOfWeek());
    cal.add(Calendar.DAY_OF_WEEK, 6);
    Date weekEndSta = cal.getTime();
    return getDayEndTime(weekEndSta);
}

获取上周开始/结束时间

public static Date getBeginDayOfLastWeek() {
    // 开始
    Date date=new Date();
    if (date==null) {
        return null;
    }
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    int dayofweek=cal.get(Calendar.DAY_OF_WEEK);
    if (dayofweek==1) {
        dayofweek+=7;
    }
    cal.add(Calendar.DATE, 2-dayofweek-7);
    return getDayStartTime(cal.getTime());
    
    // 结束
    Calendar cal=Calendar.getInstance();
    cal.setTime(getBeginDayOfLastWeek());
    cal.add(Calendar.DAY_OF_WEEK, 6);
    Date weekEndSta = cal.getTime();
    return getDayEndTime(weekEndSta);
}

获取今年是哪一年

public static Integer getNowYear(){
    Date date = new Date();
    GregorianCalendar gc=(GregorianCalendar)Calendar.getInstance();
    gc.setTime(date);
    return Integer.valueOf(gc.get(1));
}

获取本月是哪一月

public static int getNowMonth() {
    Date date = new Date();
    GregorianCalendar gc=(GregorianCalendar)Calendar.getInstance();
    gc.setTime(date);
    return gc.get(2) + 1;
}

获取本月的开始/结束时间

public static Date getBeginDayOfMonth() {
    // 开始
    Calendar calendar=Calendar.getInstance();
    calendar.set(getNowYear(), getNowMonth()-1, 1);
    return getDayStartTime(calendar.getTime());
    
    // 结束
    Calendar calendar=Calendar.getInstance();
    calendar.set(getNowYear(), getNowMonth()-1, 1);
    int day = calendar.getActualMaximum(5);
    calendar.set(getNowYear(), getNowMonth()-1, day);
    return getDayEndTime(calendar.getTime());
}

获取上月的开始/结束时间

public static Date getBeginDayOfLastMonth() {
    // 开始
    Calendar calendar=Calendar.getInstance();
    calendar.set(getNowYear(), getNowMonth()-2, 1);
    return getDayStartTime(calendar.getTime());
    
    // 结束
    Calendar calendar=Calendar.getInstance();
    calendar.set(getNowYear(), getNowMonth()-2, 1);
    int day = calendar.getActualMaximum(5);
    calendar.set(getNowYear(), getNowMonth()-2, day);
    return getDayEndTime(calendar.getTime());
}

获取本年的开始/结束时间

public static java.util.Date getBeginDayOfYear() {
    // 开始
    Calendar cal=Calendar.getInstance();
    cal.set(Calendar.YEAR, getNowYear());
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DATE, 1);
    return getDayStartTime(cal.getTime());
    
    // 结束
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, getNowYear());
    cal.set(Calendar.MONTH, Calendar.DECEMBER);
    cal.set(Calendar.DATE, 31);
    return getDayEndTime(cal.getTime());
}

两个日期相减得到的天数/毫秒数

public static int getDiffDays(Date beginDate, Date endDate) {
    // 相差天数
    if(beginDate==null||endDate==null) {
        throw new IllegalArgumentException("getDiffDays param is null!");
    }
    long diff=(endDate.getTime()-beginDate.getTime())/(1000*60*60*24);
    int days = new Long(diff).intValue();
    return days;
    
    // 相差毫秒数
    long date1ms=beginDate.getTime();
    long date2ms=endDate.getTime();
    return date2ms-date1ms;
}

获取当前日期前/后几个月的日期

Date dNow = new Date(); //当前时间
Calendar calendar = Calendar.getInstance(); //得到bai日历
calendar.setTime(dNow);//把当前时间赋给日du历
calendar.add(Calendar.MONTH, -3); //设置为前3月
Date dBefore = calendar.getTime(); //得到前3月的时间
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格zhi式
String defaultStartDate = sdf.format(dBefore); //格式化前3月的时间
String defaultEndDate = sdf.format(dNow); //格式化当前时间

获取两个日期中的最大/最小日期

public static Date max(Date beginDate, Date endDate) {
    // 最大
    if(beginDate==null) {
        return endDate;
    }
    if(endDate==null) {
        return beginDate;
    }
    if(beginDate.after(endDate)) {//beginDate日期大于endDate
        return beginDate;
    }
    return endDate;
    
    // 最小
    if(beginDate==null) {
        return endDate;
    }
    if(endDate==null) {
        return beginDate;
    }
    if(beginDate.after(endDate)) {
        return endDate;
    }
    return beginDate;
}

获取某月该季度的第一个月

public static Date getFirstSeasonDate(Date date) {
    final int[] SEASON={ 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 };
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    int sean = SEASON[cal.get(Calendar.MONTH)];
    cal.set(Calendar.MONTH, sean*3-3);
    return cal.getTime();
}

获取某个日期之后/之前几天的日期

public static Date getNextDay(Date date, int i) {
    // 之后几天
    Calendar cal=new GregorianCalendar();
    cal.setTime(date);
    cal.set(Calendar.DATE,cal.get(Calendar.DATE)+i);
    return cal.getTime();
    
    // 之前几天
    Calendar cal=new GregorianCalendar();
    cal.setTime(date);
    cal.set(Calendar.DATE, cal.get(Calendar.DATE)-i);
    return cal.getTime();
}

Date转String

public static String dateFormat(Date date) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(date);
    return dateString;
}

String转Date

/**
* 将"2015-08-31 21:08:06"型字符串转化为Date
* @param str
* @return
* @throws ParseException
*/
public static Date StringToDate(String str) throws ParseException{
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = (Date) formatter.parse(str);
    return date;
}

CST时间类型字符串格式化输出

/**
* 将CST时间类型字符串进行格式化输出
* @param str
* @return
* @throws ParseException
*/
public static String CSTFormat(String str) throws ParseException{
    SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
    Date date = (Date) formatter.parse(str);
    return dateFormat(date);
}

long转Date

public static Date LongToDare(long str) throws ParseException{
    return new Date(str * 1000);
}

当前日期是否在[startDate, endDate]区间

/**
* 判断当前日期是否在[startDate, endDate]区间
*
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
public static boolean isEffectiveDate(Date startDate, Date endDate){
    if(startDate == null || endDate == null){
        return false;
    }
    long currentTime = new Date().getTime();
    if(currentTime >= startDate.getTime()
       && currentTime <= endDate.getTime()){
        return true;
    }
    return false;
}

两个日期间的间隔天数

/**
* 得到二个日期间的间隔天数
* @param secondString:后一个日期
* @param firstString:前一个日期
* @return
*/
public static String getTwoDay(String secondString, String firstString) {
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
    long day = 0;
    try {
        java.util.Date secondTime = myFormatter.parse(secondString);
        java.util.Date firstTime = myFormatter.parse(firstString);
        day = (secondTime.getTime() - firstTime.getTime()) / (24 * 60 * 60 * 1000);
    } catch (Exception e) {
        return "";
    }
    return day + "";
}

闰年判断

/**
* 判断是否闰年
* @param ddate
* @return
*/
public static boolean isLeapYear(String ddate) {
    /**
         * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
         * 3.能被4整除同时能被100整除则不是闰年
         */
    Date d = strToDate(ddate);
    GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
    gc.setTime(d);
    int year = gc.get(Calendar.YEAR);
    if ((year % 400) == 0){
        return true;
    }else if ((year % 4) == 0){
        if ((year % 100) == 0){
            return false;
        }else{
            return true;
        }
    }else{
        return false;
    }
}

美国时间格式

/**
* 返回美国时间格式
* @param str
* @return
*/
public static String getEDate(String str) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    ParsePosition pos = new ParsePosition(0);
    Date strtodate = formatter.parse(str, pos);
    String j = strtodate.toString();
    String[] k = j.split(" ");
    return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
}

两个日期是否在同一周

/**
* 判断二个时间是否在同一个周
* @param date1
* @param date2
* @return
*/
public static boolean isSameWeekDates(Date date1, Date date2) {
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(date1);
    cal2.setTime(date2);
    int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
    if(0 == subYear) {
        if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)){
            return true;
        }
    }else if(1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
        // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
        if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)){
            return true;
        }
    }else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
        if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)){
            return true;
        }
    }
    return false;
}

获取星期几

/**
* 根据一个日期,返回是星期几的字符串
* @param sdate
* @return
*/
public static String getWeek(String sdate) {
    // 再转换为时间
    Date date = strToDate(sdate);
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    // int hour=c.get(Calendar.DAY_OF_WEEK);
    // hour中存的就是星期几了,其范围 1~7
    // 1=星期日 7=星期六,其他类推
    return new SimpleDateFormat("EEEE").format(c.getTime());
}

/**
* 根据一个日期,返回是星期几的字符串
* @param sdate
* @return
*/
public static String getWeekStr(String sdate){
    String str = "";
    str = getWeek(sdate);
    if("1".equals(str)){
        str = "星期日";
    }else if("2".equals(str)){
        str = "星期一";
    }else if("3".equals(str)){
        str = "星期二";
    }else if("4".equals(str)){
        str = "星期三";
    }else if("5".equals(str)){
        str = "星期四";
    }else if("6".equals(str)){
        str = "星期五";
    }else if("7".equals(str)){
        str = "星期六";
    }
    return str;
}

两个时间之间的天数

/**
* 两个时间之间的天数
* @param date1
* @param date2
* @return
*/
public static long getDays(String date1, String date2) {
    if (date1 == null || date1.equals(""))
        return 0;
    if (date2 == null || date2.equals(""))
        return 0;
    // 转换为标准时间
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
    java.util.Date date = null;
    java.util.Date mydate = null;
    try {
        date = myFormatter.parse(date1);
        mydate = myFormatter.parse(date2);
    } catch (Exception e) {
    }
    long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
    return day;
}
相关文章
|
监控 安全 物联网
什么是UWB定位技术?UWB定位的应用场景及功能介绍
uwb定位技术全称Ultra Wide Band,超宽带技术。uwb超宽带技术是一种全新的通信技术,与传统通信技术有极大差异。它不需要使用传统通信体制中的载波,而是通过发送和接收极窄脉冲来实现无线传输,由于脉冲时间宽度极窄,使用的带宽在500MHz以上。 后来,由于uwb定位技术穿透力强、功耗低、安全性高、定位精度高等优势,人们意识到了它在高精度定位领域的价值,uwb在工业定位领域的应用逐渐成为主流。
2700 0
java判断两个时间是不是同一天的方法、Java中判断是否是当天时间
这篇文章提供了两种Java中判断两个时间是否为同一天的方法:一种是使用Calendar类比较年、月、日,另一种是使用SimpleDateFormat类将日期格式化为"yyyyMMdd"格式后进行字符串比较。
java判断两个时间是不是同一天的方法、Java中判断是否是当天时间
|
JavaScript 前端开发 开发者
如何在 Visual Studio Code (VSCode) 中使用 ESLint 和 Prettier 检查并自动格式化 Vue.js 代码,提升代码质量和团队协作效率。
【10月更文挑战第8天】本文介绍了如何在 Visual Studio Code (VSCode) 中使用 ESLint 和 Prettier 检查并自动格式化 Vue.js 代码,提升代码质量和团队协作效率。通过安装 VSCode 插件、配置 ESLint 和 Prettier,实现代码规范检查和自动格式化,确保代码风格一致,提高可读性和维护性。
433 2
使用流排序时Comparator.reverseOrder() 和 reversed()的区别
使用流排序时Comparator.reverseOrder() 和 reversed()的区别
412 0
|
前端开发 测试技术 C++
Python自动化测试面试:unittest、pytest与Selenium详解
【4月更文挑战第19天】本文聚焦Python自动化测试面试,重点讨论unittest、pytest和Selenium三大框架。unittest涉及断言、TestSuite和覆盖率报告;易错点包括测试代码冗余和异常处理。pytest涵盖fixtures、参数化测试和插件系统,要注意避免过度依赖unittest特性。Selenium的核心是WebDriver操作、等待策略和测试报告生成,强调智能等待和元素定位策略。掌握这些关键点将有助于提升面试表现。
900 0
|
存储 数据可视化 数据挖掘
文献丨转录组表达数据的生信挖掘研究
文献丨转录组表达数据的生信挖掘研究
|
XML 缓存 前端开发
SpringBoot + MyBatis-Plus构建树形结构的几种方式
SpringBoot + MyBatis-Plus构建树形结构的几种方式
|
Ubuntu Java Shell
Android使用FFmpeg的API库
Android使用FFmpeg的API库
514 1
|
SQL 算法 Cloud Native
数据库内核那些事|细说PolarDB优化器查询变换 - join消除篇
数据库的查询优化器是整个系统的"大脑",一条SQL语句执行是否高效在不同的优化决策下可能会产生几个数量级的性能差异,因此优化器也是数据库系统中最为核心的组件和竞争力之一。阿里云瑶池旗下的云原生数据库PolarDB MySQL版作为领先的云原生数据库,希望能够应对广泛用户场景、承接各类用户负载,助力企业数据业务持续在线、数据价值不断放大,因此对优化器能力的打磨是必须要做的工作之一。 本系列将从PolarDB for MySQL的查询变换能力开始,介绍我们在这个优化器方向上逐步积累的一些工作。
11620 0
|
Java API
Java使用BigDecimal(公式精确计算)+(精度丢失问题)
Java使用BigDecimal(公式精确计算)+(精度丢失问题)
685 0
Java使用BigDecimal(公式精确计算)+(精度丢失问题)