软件编程
位置:首页>> 软件编程>> java编程>> Java时间工具类Date的常用处理方法

Java时间工具类Date的常用处理方法

作者:java李杨勇  发布时间:2022-11-08 02:37:49 

标签:Java,Date类

前言

Date 类

Date 类表示系统特定的时间戳,可以精确到毫秒。Date 对象表示时间的默认顺序是星期、月、日、小时、分、秒、年。

构造方法

Date 类有如下两个构造方法。

Date():此种形式表示分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒),使用该构造方法创建的对象可以获取本地的当前时间。

Date(long date):此种形式表示从 GMT 时间(格林尼治时间)1970 年 1 月 1 日 0 时 0 分 0 秒开始经过参数 date 指定的毫秒数。

这两个构造方法的使用示例如下:

Date date1 = new Date();    // 调用无参数构造函数
System.out.println(date1.toString());    // 输出:Wed May 18 21:24:40 CST 2016
Date date2 = new Date(60000);    // 调用含有一个long类型参数的构造函数
System.out.println(date2);    // 输出:Thu Jan 0108:01:00 CST 1970

Date 类的无参数构造方法获取的是系统当前的时间,显示的顺序为星期、月、日、小时、分、秒、年。

Date 类带 long 类型参数的构造方法获取的是距离 GMT 指定毫秒数的时间,60000 毫秒是一分钟,而 GMT(格林尼治标准时间)与 CST(中央标准时间)相差 8 小时,也就是说 1970 年 1 月 1 日 00:00:00 GMT 与 1970 年 1 月 1 日 08:00:00 CST 表示的是同一时间。 因此距离 1970 年 1 月 1 日 00:00:00 CST 一分钟的时间为 1970 年 1 月 1 日 00:01:00 CST,即使用 Date 对象表示为 Thu Jan 01 08:01:00 CST 1970。

常用方法


/**
* <li>说明: 日期时间工具类,针对日期的一些常用的处理方法。
* <li>创建日期:2022-05-04
* @author lyy
*/
public final class DateUtils {
/** 日期格式“年月日”,yyyyMMdd(如20121231)  */
public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
/** 日期格式“年-月-日”,yyyy-MM-dd(如2012-12-31)  */
public static final SimpleDateFormat yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd");
/** 默认日期格式“年-月-日”  */
   public static final SimpleDateFormat DEFAULT_FORMAT = yyyy_MM_dd;
/** 日期格式“年-月-日 时:分:秒”,yyyy-MM-dd HH:mm:ss(如2012-12-31 20:31:18)  */
public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   /** 日期格式“年-月-日 时:分:秒:毫秒”,yyyy-MM-dd HH:mm:ss(如2012-12-31 20:31:18)  */
   public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss_SSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
/** 日期格式“年-月-日 时:分”,yyyy-MM-dd HH:mm(如2012-12-31 20:31)  */
public static final SimpleDateFormat yyyy_MM_dd_HH_mm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
/** 日期格式“年月日时分秒”,yyyyMMddHHmmss(如20121231203118)  */
public static final SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
/** 日期格式“年月日时分秒毫秒”,yyyyMMddHHmmssSSS(如20121231203118978)  */
public static final SimpleDateFormat yyyyMMddHHmmssSSS = new SimpleDateFormat("yyyyMMddHHmmssSSS");
/** 日期格式“年月日时分秒毫秒”,yyyy-MM-ddHH:mm:ssSSS(如2012-12-3120:31:18523)  */
public static final SimpleDateFormat yyyy_MM_ddHH_mm_ssSSS = new SimpleDateFormat("yyyy-MM-ddHH:mm:ssSSS");
/** 日期格式“月日”,MMdd(如0121)  */
public static final SimpleDateFormat MMdd = new SimpleDateFormat("MMdd");

/**
* <li>说明:禁止实例化该类
*/
   private DateUtils() {}

/**
    * <li>说明:使用默认日期格式(yyyy-MM-dd)解析日期字符串
    * @param String date:日期字符串
    * @return Date 解析成功返回的日期对象
    * @throws ParseException
    */
   public static Date parse(String date) throws ParseException{
       return DEFAULT_FORMAT.parse(date);
   }
   /**
    * <li>说明:使用指定日期格式解析日期字符串
    * @param String date:日期字符串
    * @param String format:日期格式
    * @return Date 解析成功返回的日期对象
    * @throws ParseException
    */
   public static Date parse(String date, String format) throws ParseException{
       return new SimpleDateFormat(format).parse(date);
   }    

/**
    * <li>说明:根据格式化字符串,返回当前系统时间的字符串
    * @param String format:日期时间格式化字符串
    * @return String 当前系统时间的字符串
    * @throws
    */
   public static String getToday(String format) {
       return new SimpleDateFormat(format).format(new Date());
   }

/**
    * 根据格式化字符串,返回指定时间的字符串
    * @param date 指定时间
    * @param format 日期时间格式化SimpleDateFormat
    * @return 指定时间的字符串
    */
   public static String format(Date date, SimpleDateFormat format) {
if (date == null) {
return null;
}
return format.format(date);
   }

/**
    * <li>说明:根据格式化对象,返回当前系统时间的字符串
    * @param format 日期时间格式化对象
    * @return String 当前系统时间的字符串
    */
   public static String getToday(SimpleDateFormat format) {
       return format.format(new Date());
   }

/**
    * <li>说明:默认返回当前系统时间字符串,格式为“yyyy-MM-dd”。
    * @return String 当前系统时间字符串,格式为“yyyy-MM-dd
    * @throws
    */
   public static String getToday() {
       return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
   }
   /**
    * <li>说明:默认返回当前系统时间字符串,格式为“MMdd”。
    * @return String 当前系统时间字符串,格式为“yyyy-MM-dd
    * @throws
    */
   public static String getTodayMMdd() {
       return MMdd.format(new Date());
   }
   /**
* <li>说明:获得两个日期的月差
* @param Calendar one:第一个日历对象
* @param Calendar two:第二个日历对象
* @return int 相差的月数
* @throws
*/
public static int monthDifference(Calendar one, Calendar two) {
if (null == one || null == two) {
throw new NullPointerException("参数对象为空。");
}
Calendar after = one;
Calendar before = two;
if (one.before(two)) {
after = two;
before = one;
}
int deffYear = Math.abs(after.get(Calendar.YEAR) - before.get(Calendar.YEAR));
int deffMonth = after.get(Calendar.MONTH) - before.get(Calendar.MONTH);
/*if (deffMonth < 0) {
deffYear = deffYear - 1;
deffMonth = Math.abs(deffMonth);
}*/  //错误的逻辑块
return deffYear * 12 + deffMonth;
}

/**
* <li>说明:获得两个日期的月差
* @param Date one:第一个日期
* @param Date two:第二个日期
* @return int 相差的月数
* @throws
*/
public static int monthDifference(Date one, Date two) {
Calendar first = new GregorianCalendar();
first.setTime(one);
Calendar second = new GregorianCalendar();
second.setTime(two);
return monthDifference(first, second);
}

/**
* <li>说明:获得两个日期的月差
* @param String one:第一个日期字符串,格式必须为“yyyy-MM-dd”
* @param String two:第二个日期字符串,格式必须为“yyyy-MM-dd”
* @return int 相差的月数
* @throws ParseException
*/
public static int monthDifference(String one, String two)
throws ParseException {
Format format = new SimpleDateFormat("yyyy-MM-dd");
Date first = (java.util.Date) format.parseObject(one);
Date second = (java.util.Date) format.parseObject(two);
return monthDifference(first, second);
}

/**
* <li>说明:是否为月的最后一天
* @param Calendar calendar:日历对象
* @return boolean true=是,false=否
* @throws
*/
public static boolean isLastDayOfMonth(Calendar calendar) {
Calendar today = calendar;
Calendar tomorrow = (Calendar) calendar.clone();
tomorrow.add(Calendar.DAY_OF_MONTH, 1);
int todayYear = today.get(Calendar.YEAR);
int todayMonth = today.get(Calendar.MONTH) + 1;
int tomorrowYear = tomorrow.get(Calendar.YEAR);
int tomorrowMonth = tomorrow.get(Calendar.MONTH) + 1;
//是否为当月最后一天
if (tomorrowYear > todayYear || (tomorrowYear == todayYear && tomorrowMonth > todayMonth)) {
return true;
}
return false;
}

/**
* <li>说明: 是否为月的最后一天
* @param Date date:日期对象
* @return boolean true=是,false=否
* @throws
*/
public static boolean isLastDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return isLastDayOfMonth(calendar);
}

/**
* <li>说明:当前系统时间当天是否为月的最后一天
* @return boolean true=是,false=否
* @throws
*/
public static boolean isLastDayOfMonth() {
return isLastDayOfMonth(Calendar.getInstance());
}

/**
* <li>说明:将数字表示的月份转换位成中文表示的月份
* @param int month:数字月份
* @return String 中文月份
* @throws
*/
public static String convertMonth(int month) {
switch (month) {
case Calendar.JANUARY:
return "一月";
case Calendar.FEBRUARY:
return "二月";
case Calendar.MARCH:
return "三月";
case Calendar.APRIL:
return "四月";
case Calendar.MAY:
return "五月";
case Calendar.JUNE:
return "六月";
case Calendar.JULY:
return "七月";
case Calendar.AUGUST:
return "八月";
case Calendar.SEPTEMBER:
return "九月";
case Calendar.OCTOBER:
return "十月";
case Calendar.NOVEMBER:
return "十一月";
case Calendar.DECEMBER:
return "十二月";
default:
throw new IllegalArgumentException("表示月份的参数无效:" + month);
}
}

/**
* <li>说明:将数字表示的周天转换位成中文表示的周天
* @param int dayOfWeek:该天在一周内的数字序号,从0开始(周日0-周六6)
* @return String 返回具体周天名称
* @throws
*/
public static String convertDayOfWeek(int dayOfWeek) {
switch (dayOfWeek) {
case Calendar.SUNDAY:
return "周日";
case Calendar.MONDAY:
return "周一";
case Calendar.TUESDAY:
return "周二";
case Calendar.WEDNESDAY:
return "周三";
case Calendar.THURSDAY:
return "周四";
case Calendar.FRIDAY:
return "周五";
case Calendar.SATURDAY:
return "周六";
default:
throw new IllegalArgumentException("参数无效:" + dayOfWeek);
}
}

/**
* <li>说明:将数字表示的周天转换位成中文表示的星期
* @param int dayOfWeek:该天在一星期内的数字序号,从0开始(星期天0-星期六6)
* @return String 星期几名称
* @throws
*/
public static String convertDayOfWeek2(int dayOfWeek) {
switch (dayOfWeek) {
case Calendar.SUNDAY:
return "星期天";
case Calendar.MONDAY:
return "星期一";
case Calendar.TUESDAY:
return "星期二";
case Calendar.WEDNESDAY:
return "星期三";
case Calendar.THURSDAY:
return "星期四";
case Calendar.FRIDAY:
return "星期五";
case Calendar.SATURDAY:
return "星期六";
default:
throw new IllegalArgumentException("参数无效:" + dayOfWeek);
}
}

/**
* <li>说明:获取当天是星期几。
* 注意:不能使用new Date().getDay()获取当天在星期中的位置,应该使用Calendar.getInstance().get(Calendar.DAY_OF_WEEK)获取当天在星期中的位置
* @return String 星期几名称
* @throws
*/
public static String getTodayOfWeek2() {
return convertDayOfWeek2(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
}

/**
* <li>说明:获取当天是周几。
* 注意:不能使用new Date().getDay()获取当天在星期中的位置,应该使用Calendar.getInstance().get(Calendar.DAY_OF_WEEK)获取当天在星期中的位置
* @return String 返回具体周天名称
* @throws
*/
public static String getTodayOfWeek() {
return convertDayOfWeek(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
}  
   /**
    *
    * <li>说明:将毫秒数转换为日期格式的字符串
    * @param millSeconds 毫秒数
    * @param parseStr 日期格式化字符串 如"yyyy-MM-dd hh:mm:ss"
    * @return 日期格式的字符串
    */
   public static String getDateByMillSeconds(long millSeconds, String parseStr){        
       java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(parseStr);  
       String sb=format.format(getDateByMillSeconds(millSeconds));  
       return sb;
   }
   /**
    *
    * <li>说明:将毫秒数转换为日期
    * @param millSeconds 毫秒数
    * @return 日期
    */
   public static Date getDateByMillSeconds(long millSeconds){
       Date date = new Date(millSeconds);  
       GregorianCalendar gc = new GregorianCalendar();  
       gc.setTime(date);  
       return gc.getTime();
   }
   /**
    *
    * <li>说明:获取服务器时间,本月的第一天
    * @return 获取服务器时间,本月的第一天
    */
   public static String getFirstDayByCurrentMonth(){
       Calendar calendar  =   new  GregorianCalendar();
       calendar.set( Calendar.DATE,  1 );
       SimpleDateFormat simpleFormate  =   new  SimpleDateFormat( "yyyy-MM-dd" );
       return simpleFormate.format(calendar.getTime());
   }

/**
    *
    * <li>说明:获取服务器时间, 本月的最后一天
    * @return 获取服务器时间, 本月的最后一天
    */
   public static String getLastDayByCurrentMonth(){
       Calendar calendar  =   new  GregorianCalendar();
       calendar.set( Calendar.DATE,  1 );
       calendar.roll(Calendar.DATE,  - 1 );
       SimpleDateFormat simpleFormate  =   new  SimpleDateFormat( "yyyy-MM-dd" );
       return simpleFormate.format(calendar.getTime());
   }
   /**
    *
    * <li>说明:获取实际工期(分钟数)临时使用,以后有工作日历再做修改
    * @param realStartDate 实际开工时间
    * @param realEndDate 实际完工时间
    * @return 实际工期(分钟数)
    * @throws Exception
    */
   public static Long getRealWorkminutes(Date realStartDate, Date realEndDate) throws Exception{
       BigDecimal realWorkminutes = new BigDecimal("0");
       long startTime = 0l;
       long endTime = 0l;
       long timeInterval = 0l;
       if(realStartDate != null && realEndDate != null) {
           startTime = realStartDate.getTime();
           endTime = realEndDate.getTime();
           timeInterval = endTime - startTime;
           if(timeInterval > 0){
               int day = (int)timeInterval/(24*60*60*1000);        
               int hour = (int)timeInterval/(60*60*1000)-day*24;          
               int min = (int)(timeInterval/(60*1000))-day*24*60-hour*60;
               if(day >= 1){
                   realWorkminutes = new BigDecimal(day*8*60);
                   if(hour >= 1){
                       realWorkminutes = realWorkminutes.add(new BigDecimal(hour*20));
                   }
                   if(min >=1){
                       realWorkminutes = realWorkminutes.add(new BigDecimal(min));
                   }
               }else{
                   if(hour >= 1){
                       realWorkminutes = realWorkminutes.add(new BigDecimal(hour*60>=480?480:hour*60));
                   }
                   if(min >=1){
                       realWorkminutes = realWorkminutes.add(new BigDecimal(min));
                   }
                   if(realWorkminutes.compareTo(new BigDecimal(480)) > 0) realWorkminutes = new BigDecimal(480);
               }
           }
       }
       return Long.valueOf(String.valueOf(realWorkminutes));
   }
   /**
    * <li>说明:得到两个日期间隔的天数
    * @param String beginDate 开始日期"yyyy-MM-dd"
    * @param String endDate 结束日期"yyyy-MM-dd"
    * @return int 相差天数
    * @throws ParseException
    */
   public static int getDaysBetween(String beginDate, String endDate)
throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date bDate = format.parse(beginDate);
Date eDate = format.parse(endDate);
return getDaysBetween(bDate, eDate);
}
   /**
    * <li>说明:得到两个日期间隔的天数
    * @param Date beginDate 开始日期
    * @param Date endDate 结束日期
    * @return int 相差天数
    * @throws ParseException
    */
   public static int getDaysBetween(Date beginDate, Date endDate)
throws ParseException {
Calendar g1 = new GregorianCalendar();
g1.setTime(beginDate);
Calendar g2 = new GregorianCalendar();
g2.setTime(endDate);

int elapsed = 0;
 GregorianCalendar gc1, gc2;

if (g2.after(g1)) {
  gc2 = (GregorianCalendar) g2.clone();
  gc1 = (GregorianCalendar) g1.clone();
 } else {
  gc2 = (GregorianCalendar) g1.clone();
  gc1 = (GregorianCalendar) g2.clone();
 }

gc1.clear(Calendar.MILLISECOND);
 gc1.clear(Calendar.SECOND);
 gc1.clear(Calendar.MINUTE);
 gc1.clear(Calendar.HOUR_OF_DAY);

gc2.clear(Calendar.MILLISECOND);
 gc2.clear(Calendar.SECOND);
 gc2.clear(Calendar.MINUTE);
 gc2.clear(Calendar.HOUR_OF_DAY);

while (gc1.before(gc2)) {
  gc1.add(Calendar.DATE, 1);
  elapsed++;
 }
 return elapsed;
}    

/**
    * <li>说明:根据开始时间和时长获取完成时间
    * @param startTime 开始时间
    * @param timeInterval 时长
    * @return 完成时间
    */
   public static long getFinalTime(long startTime, long timeInterval) {
       return startTime + timeInterval;
   }

}

来源:https://blog.csdn.net/weixin_39709134/article/details/124951730

0
投稿

猜你喜欢

  • 1.初始化顺序当Java创建一个对象时,系统先为该对象的所有实例属性分配内存(前提是该类已经被加载过了),接着程序开始对这些实例属性执行初始
  • 前言:在 Java 语言中,保证线程安全性的主要手段是加锁,而 Java 中的锁主要有两种:synchronized 和 Lock,我们今天
  • 1. 准备工作需要提前安装好Elasticsearch,访问地址:http://127.0.0.1:9200/ 得到以下结果,得到clust
  • 最近在学ssh,一直搞不懂$,%,#的区别,做了点小练习,慢慢也懂了一点,将自己所学的也记录下来吧。   存在一下一个实
  • 本文实例为大家分享了Android实现APP秒表功能的具体代码,供大家参考,具体内容如下这几天一直在看安卓,也正好赶上老师布置的作业,所以就
  • ProgressBar进度条,分为旋转进度条和水平进度条,进度条的样式根据需要自定义,之前一直不明白进度条如何在实际项目中使用,网上演示进度
  • 1、打开代码管理器2、打开后就可以看到如下图所示3、复制粘贴该路径,转到该文件夹下新加一个txt文件,把下面的文本复制粘贴<?xml
  • 1.什么是灰度发布?灰度发布又称金丝雀发布,是在系统升级的时候能够平滑过渡的一种发布方式。在其上可以进行A/B测试,即让一部分用户继续用产品
  • 前言Android提供了很多种保存应用程序数据的方法。其中一种就是用SharedPreferences对象来保存我们私有的键值(key-va
  • 在C#中,得益于强大的GC机制,使得我们开发程序变得非常简单,很多时候我们只需要管使用,而并不需要关心什么时候释放资源。但是,GC有的时并不
  • MyBatis * 介绍MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是 * 功能。那么 * 拦截MyBatis
  • 最近有个粉丝提了个问题,说他在Spring Security中用JWT做退出登录的时无法获取当前用户,导致无法证明“我就是要退出的那个我”,
  • 下面一段内容有项目需求有项目分析,通过一个小demo给大家展示下C#如何对多线程、多任务管理的。项目需求:假设多个任务需要执行,每个任务不是
  • 本文实例讲述了JavaMail实现发送超文本(html)格式邮件的方法。分享给大家供大家参考。具体如下:附件以超文本形式,很常用,与普通的邮
  • RN的打包,大家可以根据官网一步一步来,但这里有几个地方注意,一下简单介绍:生成一个签名密钥在项目的目录下打开cmd命令窗口输入一下命令运行
  • 1.使用的注意事项本节给大家带来基础UI控件部分的最后一个控件:DrawerLayout,官方给我们提供的一个侧滑菜单控件,和上一节的Vie
  • Android 获取IP地址最近做项目,有一个需求是Android设备获取当前IP的功能,经过一番查询资料解决了,记录下实现方法。1.使用W
  • 背景实际开发中,常常需要将比较复杂的 JSON 字符串转换为对应的 Java 对象。这里记录下解决方案。如下所示,是入侵事件检测得到的 JS
  • 本节我们主要介绍 Ribbon 的一些常用配置和配置 Ribbon 的两种方式。常用配置1. 禁用 Eureka当我们在 RestTempl
  • 创建我们来看看,使用Arrays 怎么创建一个新的数组,一般来说,我们可以使用Arrays 的 copyOf , copyOfRange 和
手机版 软件编程 asp之家 www.aspxhome.com