Java中常用时间的一些相关方法

 更新时间:2021年10月26日 11:52:36   作者:影子930  
日期的使用多种多样,但万变不离其宗,下面这篇文章主要给大家介绍了关于Java中常用时间的一些相关方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

前言

在我们java开发中,Date日期这个字段会被经常使用,比如获取当前系统的时间,获取上个月,上一年的时间,以及获取两个日期相差的时分秒数,或者对日期类型进行格式化,等等,等等,下面将给大家详细介绍下Java中常用时间的一些相关方法

一、获取当前时间的方式

public static void main(String[] args) {
    //Date
    Date now = new Date();
    System.out.println(now);

    //java8的时间
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println(localDateTime);


    Calendar calendar = Calendar.getInstance();
    Date time = calendar.getTime();
    System.out.println(time);
    System.out.println("年" + calendar.get(Calendar.YEAR));
    System.out.println("月" + (calendar.get(Calendar.MONTH) + 1));

    //joda time
    DateTime dateTime = DateTime.now();
    System.out.println(dateTime);
}


获取当前时间可以使用Date LocalDatetime Calendar  Datetime

二、获取当月第n天

public static void main(String[] args) {
    //建议使用Calendar  可以设置年月日时分秒
    Calendar calendar = Calendar.getInstance();
    ////当月16
    calendar.set(Calendar.DAY_OF_MONTH, 16);
    System.out.println(calendar.getTime());

    //当月16
    DateTime now = DateTime.now();
    DateTime dateTime = now.withDayOfMonth(16);
    System.out.println(dateTime);

    //当月14
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println(localDateTime.withDayOfMonth(14));

    //1月11
    System.out.println(localDateTime.withMonth(1).withDayOfMonth(11));
}

三、格式化为字符串

```
//使用SimpleDateFormat
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(new Date()));

//使用Calendar
Calendar calendar = Calendar.getInstance();
System.out.println(String.format("%s年%s月%s日%s时%s分%s秒", calendar.get(Calendar.YEAR),
        calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH),
        calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)));

LocalDateTime now = LocalDateTime.now();
String str = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(str);
```

四、加减时间(单位可以是秒,小时等)

public static void main(String[] args) {
    Date now = new Date();
    //加一小时
    long time = now.getTime() + (60 * 60 * 1000);
    System.out.println(new Date(time));

    /*
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.7.14</version>
    </dependency>
     */
    //引入Hutool 加一小时
    System.out.println(DateUtil.offset(now, DateField.HOUR, 1));
    //减一小时
    System.out.println(DateUtil.offset(now, DateField.HOUR, -1));

    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("加一小时" + localDateTime.plusHours(1));
    System.out.println("减一小时" + localDateTime.minusHours(1));

    DateTime dateTime = DateTime.now();
    System.out.println(dateTime.plusHours(1));
    System.out.println(dateTime.minusHours(1));
}

LocalDateTime和DateTime都自带增加和减少时间的方法

五、通过出生日期获取年龄

public static void main(String[] args) {
    //时间1990-12-05
    DateTime birthDay = DateTime.now().withYear(1990).withMonthOfYear(10).withDayOfMonth(23);
    System.out.println(birthDay);
    //获取相差得年 会进行月份和日期比较 如
    Years years = Years.yearsBetween(birthDay, new DateTime());
    System.out.println(years);
    System.out.println(years.getYears());
}

还可以使用年份相减,再比较月,日的方法得到生日

六、判断两个时间段是否覆盖

public static void main(String[] args) {
    DateTime now = DateTime.now();

    DateTime start1 = now;
    DateTime end1 = now.plusMinutes(1);

    DateTime start2 = now.plusSeconds(50);
    DateTime end2 = now.plusMinutes(2);

    Interval interval1 = new Interval(start1, end1);
    Interval interval2 = new Interval(start2, end2);

    System.out.println(interval1.overlaps(interval2));
    System.out.println(start1.getMillis() < end2.getMillis() && start2.getMillis() < end1.getMillis());
}

七、求两个时间间隔

public static void main(String[] args) {
    DateTime now = DateTime.now();
    //开始时间
    Date startTime = now.toDate();
    //结束时间
    Date endTime = now.plusHours(1).toDate();
    //1小时
    System.out.println("开始时间与结束时间的时间间隔:" + DateUtil.between(startTime, endTime, DateUnit.SECOND));

    long time = (endTime.getTime() - startTime.getTime()) / 1000;
    System.out.println(time);
}

八、UTC时间与北京时间转换

public static void main(String[] args) throws ParseException {
    Date now = new Date();
    Date utcDate = bj2UTC(now);
    //utc时间 
    System.out.println(utcDate);
    //北京时间
    System.out.println(utc2BJ(utcDate));

    DateTime dateTime = DateTime.now().withDayOfMonth(1).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
    System.out.println(dateTime);
    System.out.println(bj2UTC(dateTime.toDate()));
}

public static Date bj2UTC(Date date) {
    if (date == null) {
        return null;
    }
    LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.of("-8"));
    return Date.from(localDateTime.atOffset(ZoneOffset.UTC).toInstant());
}

public static Date utc2BJ(Date date) {
    if (date == null) {
        return null;
    }
    LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.of("+8"));
    return Date.from(localDateTime.atOffset(ZoneOffset.UTC).toInstant());
}

北京时间=UTC+8

总结

到此这篇关于Java中常用时间的一些相关方法的文章就介绍到这了,更多相关Java常用时间方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot之跨域过滤器配置允许跨域访问方式

    SpringBoot之跨域过滤器配置允许跨域访问方式

    这篇文章主要介绍了SpringBoot之跨域过滤器配置允许跨域访问方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • 为Java应用创建Docker镜像的3种方式总结

    为Java应用创建Docker镜像的3种方式总结

    Docker的使用可以将应用程序做成镜像,这样可以将镜像发布到私有或者公有仓库中,在其他主机上也可以pull镜像,并且运行容器,运行程,下面这篇文章主要给大家总结介绍了关于为Java应用创建Docker镜像的3种方式,需要的朋友可以参考下
    2023-06-06
  • SpringBoot文件分片上传教程

    SpringBoot文件分片上传教程

    这篇文章主要介绍了SpringBoot文件分片上传教程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • 解决myBatis中openSession()自动提交的问题

    解决myBatis中openSession()自动提交的问题

    在学习MySQL过程中,发现插入操作自动提交,问题原因可能是myBatis中的openSession()方法设置了自动提交,或者是MySQL的默认引擎设置为不支持事务的MyISAM,解决办法包括更改myBatis的提交设置或将MySQL表的引擎改为InnoDB
    2024-09-09
  • springboot登陆过滤功能的实现代码

    springboot登陆过滤功能的实现代码

    这篇文章主要介绍了springboot登陆过滤功能的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • Java中String类使用方法总结

    Java中String类使用方法总结

    这篇文章主要介绍了Java中String类的使用方法,文章简单易懂,结尾有实例代码帮助大家理解学习,感兴趣的朋友可以了解下
    2020-06-06
  • SpringCloud OpenFeign基本介绍与实现示例

    SpringCloud OpenFeign基本介绍与实现示例

    OpenFeign源于Netflix的Feign,是http通信的客户端。屏蔽了网络通信的细节,直接面向接口的方式开发,让开发者感知不到网络通信细节。所有远程调用,都像调用本地方法一样完成
    2023-02-02
  • java数据结构排序算法之树形选择排序详解

    java数据结构排序算法之树形选择排序详解

    这篇文章主要介绍了java数据结构排序算法之树形选择排序,结合具体实例形式分析了java树形选择排序的原理、实现技巧与相关注意事项,需要的朋友可以参考下
    2017-05-05
  • 从dubbo源码分析qos-server端口冲突问题及解决

    从dubbo源码分析qos-server端口冲突问题及解决

    这篇文章主要介绍了从dubbo源码分析qos-server端口冲突问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • SpringBoot整合POI实现Excel文件读写操作

    SpringBoot整合POI实现Excel文件读写操作

    EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具,这篇文章主要介绍了SpringBoot整合POI实现Excel文件读写操作,首先准备环境进行一系列操作,本文给大家介绍的非常详细,需要的朋友参考下吧
    2023-10-10

最新评论