Java中常用时间的一些相关方法
作者:影子930 发布时间:2022-02-06 11:33:38
标签: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
来源:https://juejin.cn/post/7022923059992461320


猜你喜欢
- ScrollConfiguration( behavior: NoScrollBehaviorWidget(),
- 安装 Tomcat 之前请一定先安装 Java ,然后才能安装 Tomcat 。安装 Java 、环境变量 path 的设置以及 cmd 小
- 图像切换器(ImageSwitcher),用于实现类似于Windows操作系统的“Windows照片查看器”中的上一张、下一张切换图片的功能
- 一、背景在上一篇文章中,我们使用Seata整合了SpringBoot,在这篇文章中我们使用Seata整合SpringCloud。同时有了上一
- 下面通过代码给大家介绍c++ string insert() 函数,具体内容如下:basic_string& inser
- 前言文件上传是项目开发中最常见的功能之一 ,SpringMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配Multi
- 思路:先从集合中找出来顶级的菜单,然后遍历顶级菜单,找出每个顶级菜单的所有子菜单,然后判断当前需要排列的集合是否为空,如果不为空的话,就在遍
- spring的refresh方法前置知识方法入口// org.springframework.context.support.Abstrac
- List集合转Map,用到的是Stream中Collectors的toMap方法:Collectors.toMap具体用法实例如下://声明
- public bool isUtf8(byte[] rawText)
- 直接上代码新建DecimalInputTextWatcher类继承TextWatcher (代码可直接复制使用) import androi
- 实践过程效果代码public partial class Form1 : Form{ public Form1()
- 下面给大家分享一个有趣的动画:这里比较适合一张图片的翻转,如果是多张图片,可以参考APIDemo里的例子,就是加个ArrayAdapter,
- 我们知道,使用nginx作为文件下载服务器,可以极大地降低对后端Java服务器的负载冲击,但是nginx本身并不提供授权控制,因此好的方案是
- 之前学习oracle,简单的认为数据库只存在服务器端,学习安卓之后才发现原来android和Ios本身是“携带”数据库的——SQ
- 实现Android 滑动退出Activity的功能android向右滑动,退出activity//右滑删除 compile &
- 前言工作中是否遇到这样的场景?1、需要异步线程执行,而且需要获取到线程执行返回的结果。2、如果执行过程异常,可以按照自定义方式消费异常信息。
- 1、for循环虽然所有循环结构都可以用 while 或者 do…while来表示,但 for 循环的出现,可使一些循环
- Java数组声明、创建、初始化一维数组的声明方式:type var[]; 或type[] var;声明数组时不能指定其长度(数组中元素的个数
- 这篇文章主要介绍了JAVA泛型的继承和实现、擦除原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的