Ⅰ java中如何計算出兩個日期之間相差多少天
思路就是根據它們相差的毫秒數除以每天的毫秒數(60*60*24*1000),代碼如下:
public static void main(String[] args) throws ParseException {
String date1="1987-01-01";
String date2="2010-01-01";
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
Date d1=sdf.parse(date1);
Date d2=sdf.parse(date2);
long daysBetween=(d2.getTime()-d1.getTime()+1000000)/(60*60*24*1000);
System.out.println("1987-01-01 與 2010-01-01 相隔 "+daysBetween+" 天");
}
運行結果如下:
(1)java比較日期差擴展閱讀:
Java使用以下三種方法來比較兩個日期:
1、使用 getTime() 方法獲取兩個日期(自1970年1月1日經歷的毫秒數值),然後比較這兩個值。
2、使用方法 before(),after() 和 equals()。例如,一個月的12號比18號早,則 new Date(99, 2, 12).before(new Date (99, 2, 18)) 返回true。
3、使用 compareTo() 方法,它是由 Comparable 介面定義的,Date 類實現了這個介面。
SimpleDateFormat 是一個以語言環境敏感的方式來格式化和分析日期的類。SimpleDateFormat 允許你選擇任何用戶自定義日期時間格式來運行
例如:
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
這一行代碼確立了轉換的格式,其中 yyyy 是完整的公元年,MM 是月份,dd 是日期,HH:mm:ss 是時、分、秒。
注意:有的格式大寫,有的格式小寫,例如 MM 是月份,mm 是分;HH 是 24 小時制,而 hh 是 12 小時制。
以上實例編譯運行結果如下:
當前時間為: 2018-09-14 10:16:34
菜鳥教程-Java 日期時間
Ⅱ java如何判斷兩個日期字元串相差多少天
沒有這樣的函數,但是你自己可以封裝一個這樣的函數。
一般來說,並不計算兩個日期相差的月數以及年數,因為月的天數以及年的天數並不是固定的,所以很多倒計時最多計算到天。
函數體:
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
String a="20140301";
String b = "20140225";
Long c = sf.parse(b).getTime()-sf.parse(a).getTime();
long d = c/1000/60/60/24;//天
System.out.println(d+"天");
只要將a,b當做參數傳過去,將天數返回就可以
Ⅲ java中計算兩個日期之間差的天數
在Java開發物流或是其他功能的時候會用到兩個日期相差多天的數據,所以整理了一下備用。
調用方式:
代碼如下 復制代碼
long date1 = getDateTime("20121201");//可改成自己的日期類型,但以「20121212」這種格式
long date2 = getDateTime("20121212");
int day = dateInterval(date1, date2);
System.out.println(day);
具體實現方法調用:
代碼如下 復制代碼
/**
* 計算出兩個日期之間相差的天數
* 建議date1 大於 date2 這樣計算的值為正數
* @param date1 日期1
* @param date2 日期2
* @return date1 - date2
*/
public static int dateInterval(long date1, long date2) {
if(date2 > date1){
date2 = date2 + date1;
date1 = date2 - date1;
date2 = date2 - date1;
}
// Canlendar 該類是一個抽象類
// 提供了豐富的日歷欄位
// 本程序中使用到了
// Calendar.YEAR 日期中的年份
// Calendar.DAY_OF_YEAR 當前年中的天數
// getActualMaximum(Calendar.DAY_OF_YEAR) 返回今年是 365 天還是366天
Calendar calendar1 = Calendar.getInstance(); // 獲得一個日歷
calendar1.setTimeInMillis(date1); // 用給定的 long 值設置此 Calendar 的當前時間值。
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(date2);
// 先判斷是否同年
int y1 = calendar1.get(Calendar.YEAR);
int y2 = calendar2.get(Calendar.YEAR);
int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
int maxDays = 0;
int day = 0;
if(y1 - y2 > 0){
day = numerical(maxDays, d1, d2, y1, y2, calendar2);
}else{
day = d1 - d2;
}
return day;
}
/**
* 日期間隔計算
* 計算公式(示例):
* 20121201- 20121212
* 取出20121201這一年過了多少天 d1 = 天數 取出20121212這一年過了多少天 d2 = 天數
* 如果2012年這一年有366天就要讓間隔的天數+1,因為2月份有29日。
* @param maxDays 用於記錄一年中有365天還是366天
* @param d1 表示在這年中過了多少天
* @param d2 表示在這年中過了多少天
* @param y1 當前為2012年
* @param y2 當前為2012年
* @param calendar 根據日歷對象來獲取一年中有多少天
* @return 計算後日期間隔的天數
*/
public static int numerical(int maxDays, int d1, int d2, int y1, int y2, Calendar calendar){
int day = d1 - d2;
int betweenYears = y1 - y2;
List d366 = new ArrayList();
if(calendar.getActualMaximum(Calendar.DAY_OF_YEAR) == 366){
System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_YEAR));
day += 1;
}
for (int i = 0; i < betweenYears; i++) {
// 當年 + 1 設置下一年中有多少天
calendar.set(Calendar.YEAR, (calendar.get(Calendar.YEAR)) + 1);
maxDays = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
// 第一個 366 天不用 + 1 將所有366記錄,先不進行加入然後再少加一個
if(maxDays != 366){
day += maxDays;
}else{
d366.add(maxDays);
}
// 如果最後一個 maxDays 等於366 day - 1
if(i == betweenYears-1 && betweenYears > 1 && maxDays == 366){
day -= 1;
}
}
for(int i = 0; i < d366.size(); i++){
// 一個或一個以上的366天
if(d366.size() >= 1){
day += d366.get(i);
}
}
return day;
}
/**
* 將日期字元串裝換成日期
* @param strDate 日期支持年月日 示例:yyyyMMdd
* @return 1970年1月1日器日期的毫秒數
*/
public static long getDateTime(String strDate) {
return getDateByFormat(strDate, "yyyyMMdd").getTime();
}
/**
* @param strDate 日期字元串
* @param format 日期格式
* @return Date
*/
public static Date getDateByFormat(String strDate, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try{
return (sdf.parse(strDate));
}catch (Exception e){
return null;
}
}
例2
代碼如下 復制代碼
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class test16 {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1=sdf.parse("2012-09-08 10:10:10");
Date d2=sdf.parse("2012-09-15 00:00:00");
System.out.println(daysBetween(d1,d2));
System.out.println(daysBetween("2012-09-08 10:10:10","2012-09-15 00:00:00"));
}
/**
* 計算兩個日期之間相差的天數
* @param smdate 較小的時間
* @param bdate 較大的時間
* @return 相差天數
* @throws ParseException
*/
public static int daysBetween(Date smdate,Date bdate) throws ParseException
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
smdate=sdf.parse(sdf.format(smdate));
bdate=sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
*字元串的日期格式的計算
*/
public static int daysBetween(String smdate,String bdate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
}
例3
代碼如下 復制代碼
//取得剩餘天數
SimpleDateFormat df=new SimpleDateFormat("yyyymmdd");
Date d0=new java.util.Date();
Date d1=df.parse(end_date);
long time0=d0.getTime();
long time1=d1.getTime();
System.out.println((time1-time0)/(1000*60*60*24));
這樣算兩個時間相差的天數比較好
代碼如下 復制代碼
/**
* 計算兩個日期之間相差的天數
*
* @param date1
* @param date2
* @return
*/
public static int diffdates(Date date1, Date date2) {
int result = 0;
ElapsedTime et = new ElapsedTime();
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc1.setTime(date1);
gc2.setTime(date2);
result = et.getDays(gc1, gc2);
return result;
}
然後ElapseTime中的方法是:
代碼如下 復制代碼
public int getDays(GregorianCalendar g1, GregorianCalendar g2) {
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;
}
其實使用joda最簡單
代碼如下 復制代碼
public boolean isRentalOvere(DateTime datetimeRented) {
Period rentalPeriod = Period.days(2);
return datetimeRented.plus(rentalPeriod).isBeforeNow()
}
Ⅳ Java比較兩個時間相差多少天,多少個月,多少年
java比較兩個時間相差,可以使用calender類的api,實例如下:
package com.test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @description 日期比較天 月 年
* @author www.javawind.net
*/
public class DateTest {
public static void main(String[] args) {
String date = "2008-06-12";
DateTest.compareDate(date, null, 0);
DateTest.compareDate(date, null, 1);
DateTest.compareDate(date, null, 2);
date = "2006-06-03";
DateTest.compareDate(date, null, 0);
DateTest.compareDate(date, null, 1);
DateTest.compareDate(date, null, 2);
DateTest.compareDate(date, "2009-06-01", 0);
DateTest.compareDate(date, "2009-06-01", 1);
DateTest.compareDate(date, "2009-06-01", 2);
}
/**
* @param date1 需要比較的時間 不能為空(null),需要正確的日期格式
* @param date2 被比較的時間 為空(null)則為當前時間
* @param stype 返回值類型 0為多少天,1為多少個月,2為多少年
* @return
*/
public static int compareDate(String date1,String date2,int stype){
int n = 0;
String[] u = {"天","月","年"};
String formatStyle = stype==1?"yyyy-MM":"yyyy-MM-dd";
date2 = date2==null?DateTest.getCurrentDate():date2;
DateFormat df = new SimpleDateFormat(formatStyle);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try {
c1.setTime(df.parse(date1));
c2.setTime(df.parse(date2));
} catch (Exception e3) {
System.out.println("wrong occured");
}
//List list = new ArrayList();
while (!c1.after(c2)) { // 循環對比,直到相等,n 就是所要的結果
//list.add(df.format(c1.getTime())); // 這里可以把間隔的日期存到數組中 列印出來
n++;
if(stype==1){
c1.add(Calendar.MONTH, 1); // 比較月份,月份+1
}
else{
c1.add(Calendar.DATE, 1); // 比較天數,日期+1
}
}
n = n-1;
if(stype==2){
n = (int)n/365;
}
System.out.println(date1+" -- "+date2+" 相差多少"+u[stype]+":"+n);
return n;
}
/**
* 得到當前日期
* @return
*/
public static String getCurrentDate() {
Calendar c = Calendar.getInstance();
Date date = c.getTime();
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
return simple.format(date);
}
}
運行結果:
2008-06-12 -- 2009-06-09 相差多少天:362
2008-06-12 -- 2009-06-09 相差多少月:12
2008-06-12 -- 2009-06-09 相差多少年:0
2006-06-03 -- 2009-06-09 相差多少天:1102
2006-06-03 -- 2009-06-09 相差多少月:36
2006-06-03 -- 2009-06-09 相差多少年:3
2006-06-03 -- 2009-06-01 相差多少天:1094
2006-06-03 -- 2009-06-01 相差多少月:36
2006-06-03 -- 2009-06-01 相差多少年:2
可以參考上面的程序,如果還有什麼不明白的,可以自己去ITjob網上看看,有介紹Java這方面的知識。
Ⅳ java 中怎麼比較兩個時間相差的秒數
方法:
java 計算兩個時間相差可以用getTime()來獲得兩個時間的毫秒數,可以這樣計算得出兩個時間的秒數的相差如下:
public int calLastedTime(Date startDate) {long a = new Date().getTime();long b = startDate.getTime();int c = (int)((a - b) / 1000);return c;}
(5)java比較日期差擴展閱讀:
1、通過Date類來獲取當前時間
Date day=new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(day));
2、通過System類中的currentTimeMillis方法來獲取當前時間
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(df.format(System.currentTimeMillis()));
3、通過Calendar類來獲取當前時間
Calendar c = Calendar.getInstance();//可以對每個時間域單獨修改
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
System.out.println(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second);
4、 通過Date類來獲取當前時間
Date date = new Date();
String year = String.format("%tY", date);
String month = String.format("%tB", date);
String day = String.format("%te", date);
System.out.println("今天是:"+year+"-"+month+"-"+day);
Ⅵ java計算時間差
現在是2004-03-26 13:31:40
過去是:2004-01-02 11:30:24
要獲得兩個日期差,差的形式為:XX天XX小時XX分XX秒
方法一:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
{
Date d1 = df.parse("2004-03-26 13:31:40");
Date d2 = df.parse("2004-01-02 11:30:24");
long diff = d1.getTime() - d2.getTime();
long days = diff / (1000 * 60 * 60 * 24);
}
catch (Exception e)
{
}
方法二:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date now = df.parse("2004-03-26 13:31:40");
java.util.Date date=df.parse("2004-01-02 11:30:24");
long l=now.getTime()-date.getTime();
long day=l/(24*60*60*1000);
long hour=(l/(60*60*1000)-day*24);
long min=((l/(60*1000))-day*24*60-hour*60);
long s=(l/1000-day*24*60*60-hour*60*60-min*60);
System.out.println(""+day+"天"+hour+"小時"+min+"分"+s+"秒");
方法三:
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date begin=dfs.parse("2004-01-02 11:30:24");
java.util.Date end = dfs.parse("2004-03-26 13:31:40");
long between=(end.getTime()-begin.getTime())/1000;//除以1000是為了轉換成秒
long day1=between/(24*3600);
long hour1=between%(24*3600)/3600;
long minute1=between%3600/60;
long second1=between%60/60;
System.out.println(""+day1+"天"+hour1+"小時"+minute1+"分"+second1+"秒");
Ⅶ Java計算兩個日期時間相差幾天,幾小時,幾分鍾等
思路是先計算兩個日期相差的毫秒數,然後分別根據每天的毫秒數、每小時的毫秒數、每分鍾的毫秒數來計算相差幾天,幾小時,幾分鍾。具體代碼如下:
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;//每天毫秒數
long nh = 1000 * 60 * 60;//每小時毫秒數
long nm = 1000 * 60;//每分鍾毫秒數
long diff = endDate.getTime() - nowDate.getTime();// 獲得兩個時間的毫秒時間差異
long day = diff / nd; // 計算差多少天
long hour = diff % nd / nh;// 計算差多少小時
long min = diff % nd % nh / nm; // 計算差多少分鍾
return day + "天" + hour + "小時" + min + "分鍾";
}
然後做一個測試,調用這個方法測試一下:
可以看出兩個日期時間相差幾天,幾小時,幾分鍾都可以算出來。
(7)java比較日期差擴展閱讀:
Java使用以下三種方法來比較兩個日期:
1、使用 getTime() 方法獲取兩個日期(自1970年1月1日經歷的毫秒數值),然後比較這兩個值。
2、使用方法 before(),after() 和 equals()。例如,一個月的12號比18號早,則 new Date(99, 2, 12).before(new Date (99, 2, 18)) 返回true。
3、使用 compareTo() 方法,它是由 Comparable 介面定義的,Date 類實現了這個介面。
Ⅷ Java 中,如何計算兩個日期之間的差距
java.util.Date有getTime()返回一個毫秒值,,,,,,兩個Date的毫秒值相差,是毫秒級的時間差————轉成需要的單位即可以
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ⅸ java怎麼計算兩個日期相差幾天
java可以使用計算日期的天數差,以下是詳細代碼:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class test16 {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1=sdf.parse("2012-09-08 10:10:10");
Date d2=sdf.parse("2012-09-15 00:00:00");
System.out.println(daysBetween(d1,d2));
System.out.println(daysBetween("2012-09-08 10:10:10","2012-09-15 00:00:00"));
}
/**
* 計算兩個日期之間相差的天數
* @param smdate 較小的時間
* @param bdate 較大的時間
* @return 相差天數
* @throws ParseException
*/
public static int daysBetween(Date smdate,Date bdate) throws ParseException
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
smdate=sdf.parse(sdf.format(smdate));
bdate=sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
*字元串的日期格式的計算
*/
public static int daysBetween(String smdate,String bdate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
}