栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java如何获取两个日期的时间差

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java如何获取两个日期的时间差

本文实例为大家分享了java如何获取两个日期的时间差,供大家参考,具体内容如下

rainBeginTime是从本地数据库获取的时间,格式为”yyyy-MM-ddTHH:mm:ss“。

主要逻辑:

 @SuppressLint("SimpleDateFormat")
 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 df.setTimeZone(TimeZone.getTimeZone("GMT+08"));// 这里一定要设置GMT时区
 String currentTime = df.format(new Date());
 Date date1 = MyDateUtil.parseDate(trainBeginTime.replace("T"," "), "yyyy-MM-dd HH:mm:ss");
 Date date2 = MyDateUtil.parseDate(currentTime, "yyyy-MM-dd HH:mm:ss");
 // 获取相差的天数
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(date1);
 long timeInMillis1 = calendar.getTimeInMillis();
 calendar.setTime(date2);
 long timeInMillis2 = calendar.getTimeInMillis();
 long betweenDays = ((timeInMillis2 - timeInMillis1) / (1000L*3600L*24L))+2;
textView.setText("时间相差"+betweenDays+"天");

其中MyDateUtil.java:

import android.os.Build;
import androidx.annotation.RequiresApi;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;


public class MyDateUtil {
 
 public static Date parseDate(String dateStr, String pattern)
 {
 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
 Date date;
 try {
  date = sdf.parse(dateStr);
 } catch (ParseException e) {
  throw new RuntimeException("日期转化错误");
 }
 return date;
 }
 
 public static String dateFormate(Date date, String pattern)
 {
 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
 String dateStr;
 if(date == null)
 {
  return "";
 }
 dateStr = sdf.format(date);
 return dateStr;
 }
 
 public static Date incr(Date date, int days)
 {
 if (date == null){
  return null;
 }
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(date);
 calendar.add(Calendar.DAY_OF_MONTH, days);
 return calendar.getTime();
 }

 
 @RequiresApi(api = Build.VERSION_CODES.O)
 public static Date localDateToDate(LocalDate localDate)
 {
 if (localDate == null)
 {
  return null;
 }
 ZoneId zoneId = ZoneId.systemDefault();
 ZonedDateTime zonedDateTime = localDate.atStartOfDay(zoneId);
 Date date = Date.from(zonedDateTime.toInstant());
 return date;
 }
 
 @RequiresApi(api = Build.VERSION_CODES.O)
 public static LocalDate dateToLocalDate(Date date)
 {
 if (date == null)
 {
  return null;
 }
 ZoneId zoneId = ZoneId.systemDefault();
 Instant instant = date.toInstant();
 LocalDate localDate = instant.atZone(zoneId).toLocalDate();
 return localDate;
 }
}

更多关于java时间操作的文章,请点击专题:《java时间操作》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133276.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号