Java编写时间工具类ZTDateTimeUtil的示例代码

 更新时间:2023年11月10日 14:24:18   作者:Recently 祝祝  
这篇文章主要为大家详细介绍了如何利用Java编写时间工具类ZTDateTimeUtil,文中的示例代码讲解详细,有需要的小伙伴可以跟随小编一起学习一下

1.返回指定格式的当前时间,Date-->FormatString,Date类型转Strig

 Date date = new Date();
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 String datestring  = simpleDateFormat.format(date);
 System.out.printf(datestring);

2.返回固定格式的Date类型时间Date---》ToString---》ToDate,Date类型格式化成Date

public  static String TimeFormat ="yyyy-MM-dd";
    public static void main(String[] args) {
        Date date =new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TimeFormat);
        String dateformat=simpleDateFormat.format(date);
        System.out.printf(dateformat);
        Date dateafterFormat =null;
        try {
            dateafterFormat=simpleDateFormat.parse(dateformat);
            System.out.printf(String.valueOf(dateafterFormat));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

3.字符串转日期 String格式化成String

//parse(String text, ParsePosition pos)
//解析字符串中的文本以Date生成,parase需要背用try-catch包围
 String dateTime ="2023-01-16 17:35:16";
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
        Date date =simpleDateFormat.parse(dateTime);
        System.out.printf(date.toString());
    } catch (ParseException e) {
        throw new RuntimeException(e);
}

4.两时间关系判断构件

 //时间相等返回0,time1大于time2返回1,time1小于time2返回-1
  Date time1 = new Date(System.currentTimeMillis());
  String date ="2023-01-17 17:35:16";
   Date time2 = null;
   try {
       time2 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
   } catch (ParseException e) {
       throw new RuntimeException(e);
   }
   int flag =time1.compareTo(time2);
   System.out.printf(flag+"");

5.Date转换为字符串:Date格式化成String

 public static String date2Str(Date date, String format) {
        if (null == date) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
}

6.String类型时间戳格式化成日期格式String

public static String changesStringTimestamToformat(String timestamp){
        LocalDateTime parse = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(timestamp)), ZoneId.systemDefault());
        String format = parse.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
        return format;
    }

知识补充

时间格式化工具类:时间格式化工具,一秒前,一分钟前,一小时前,昨天,一天前

package com.awifi.cloudnative.container.rbac.user.provider.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
* @Author 张鑫
* @Date 2022/4/20
* @Param 
* @return 
**/
public class dataFormatUtils {
   
   
   /**
    * 时间格式化
    *
    * @param date
    * @return
    */
   public static String format(Date date) {
       // 计算出相差天数
       int days = differentDays(date, new Date());
       // 同一天
       if (0 == days) {
           // 计算出时间差
           long delta = new Date().getTime() - date.getTime();
           // 小于一分钟
           if (delta < 1L * 60000L) {
               long seconds = toSeconds(delta);
               return (seconds <= 0 ? 1 : seconds) + "秒前";
           }
           // 小于一小时
           else if (delta < 1L * 3600000L) {
               long minutes = toMinutes(delta);
               return (minutes <= 0 ? 1 : minutes) + "分钟前";
           }
           // 小于24小时
           else if (delta < 24L * 3600000L) {
               long hours = toHours(delta);
               return (hours <= 0 ? 1 : hours) + "小时前";
           }
       }
       // 不同一天
       else {
           if (1 == days) {
               return "昨天";
           }
           // 几天前
           else if (3 >= days) {
               return days + "天前";
           }
       }
       // 格式化时间
       return getYmdHm(date);
   }

   /**
    * 获取秒
    *
    * @param date
    * @return
    */
   private static long toSeconds(long date) {
       return date / 1000L;
   }

   /**
    * 获取分钟
    *
    * @param date
    * @return
    */
   private static long toMinutes(long date) {
       return toSeconds(date) / 60L;
   }

   /**
    * 获取小时
    *
    * @param date
    * @return
    */
   private static long toHours(long date) {
       return toMinutes(date) / 60L;
   }

   /**
    * 时间格式化,yyyy-MM-dd HH:mm
    */
   public static String getYmdHm(Date date) {
       DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
       return df.format(date);
   }

   /**
    * 获取天数
    *
    * @param oldDate
    * @param newDate
    * @return
    */
   public static int differentDays(Date oldDate, Date newDate) {
       Calendar oldCal = Calendar.getInstance();
       oldCal.setTime(oldDate);

       Calendar newCal = Calendar.getInstance();
       newCal.setTime(newDate);
       int oldDay = oldCal.get(Calendar.DAY_OF_YEAR);
       int newDay = newCal.get(Calendar.DAY_OF_YEAR);

       int oldYear = oldCal.get(Calendar.YEAR);
       int newYear = newCal.get(Calendar.YEAR);
       // 不是同一年
       if (oldYear != newYear) {
           int timeDistance = 0;
           for (int i = oldYear; i < newYear; i++) {
               //如果是闰年
               if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                   timeDistance += 366;
               }
               //不是闰年
               else {
                   timeDistance += 365;
               }
           }
           return timeDistance + (newDay - oldDay);
       }
       // 是同一年
       else {
           return newDay - oldDay;
       }
   }
}

到此这篇关于Java编写时间工具类ZTDateTimeUtil的示例代码的文章就介绍到这了,更多相关Java时间工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot Maven升级自带的jar包版本问题

    SpringBoot Maven升级自带的jar包版本问题

    这篇文章主要介绍了SpringBoot Maven升级自带的jar包版本问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Java实现byte[]转List的示例代码

    Java实现byte[]转List的示例代码

    byte,即字节,由8位的二进制组成。在Java中,byte类型的数据是8位带符号的二进制数。List 是一个接口,它继承于Collection的接口。它代表着有序的队列。本文将介绍如何通过java实现byte[]转List,需要的可以参考一下
    2022-01-01
  • Java Web使用Html5 FormData实现多文件上传功能

    Java Web使用Html5 FormData实现多文件上传功能

    这篇文章主要介绍了Java Web使用Html5 FormData实现多文件上传功能,需要的朋友可以参考下
    2017-07-07
  • 详解Spring Cloud Gateway基于服务发现的默认路由规则

    详解Spring Cloud Gateway基于服务发现的默认路由规则

    这篇文章主要介绍了详解Spring Cloud Gateway基于服务发现的默认路由规则,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • Java如何将大文件切割成小文件

    Java如何将大文件切割成小文件

    这篇文章主要为大家详细介绍了Java如何将大文件切割成小文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-05-05
  • Java中的5种同步辅助类介绍

    Java中的5种同步辅助类介绍

    你提交了一些任务,但你想等它们都完成了再做另外一些事情;你提交了一些任务,但是不想让它们立刻执行,等你喊123开始的时候,它们才开始执行;等等这些场景,线程之间需要相互配合,或者等待某一个条件成熟执行。这些场景想你就需要用到同步辅助类
    2014-04-04
  • Spring实现声明式事务的方法详解

    Spring实现声明式事务的方法详解

    这篇文章主要介绍了Spring实现声明式事务的方法详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • MyBatis 中使用 Mapper 简化代码的方法

    MyBatis 中使用 Mapper 简化代码的方法

    这篇文章主要介绍了MyBatis 中使用 Mapper 简化代码的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • Java中的FutureTask源码解析

    Java中的FutureTask源码解析

    这篇文章主要介绍了Java中的FutureTask源码解析,FutureTask是一个可取消的异步计算,这个类是Future的实现类,有开始和取消一个计算的方法,如果一个计算已经完成可以查看结果,需要的朋友可以参考下
    2023-12-12
  • Java缩略图生成库之Thumbnailator应用说明

    Java缩略图生成库之Thumbnailator应用说明

    Thumbnailator是一个为Java界面更流畅的缩略图生成库,从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,两三行代码就能够从现有图片生成缩略图,使用起来非常方便,需要的朋友可以了解下
    2012-12-12

最新评论