`
roddy
  • 浏览: 17584 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Get Difference Between Two Dates

    博客分类:
  • Java
 
阅读更多
引用

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class BaseModel {
    /**
     * @Des for view mode to show friendly record date.
     * @param modTs(record data time)
     * @return Today, Yesterday, More than 1 week ...
     */
    public String getFriendStr(Timestamp modTs) {
        Date todayDate = new Date();
        Date recordDate = new Date();
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat();
        df.applyPattern("yyyy-MM-dd");
        try {
            recordDate = df.parse(modTs.toString());
            todayDate = df.parse(todayDate.toString());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String friendlyStr = "";
        int countDays = this.daysBetween(recordDate,todayDate);
        int countMonths = this.getDateDif(recordDate,todayDate)[1];
        
        if(countDays>100 || countMonths>2){
            friendlyStr = "More than 3 months";
        }else if(countMonths == 1 || countMonths == 2){
            friendlyStr = "More than 1 month";
        }else if(countDays >= 14){
            friendlyStr = "More than 2 weeks";
        }else if(countDays >= 7){
            friendlyStr = "More than 1 week";
        }else if(countDays >= 4 && countDays = 3){
            friendlyStr = "3 days before";
        }else if(countDays >= 1){
            friendlyStr = "Yesterday";
        }else {
            friendlyStr = "Today";
            /*df.applyPattern("HH:mm:ss");
            friendlyStr = df.format(modTs);*/
        }
        return friendlyStr;
    }
    /**
     * @Des: Get Difference Between Two Dates in Days, Months and Year format.
     * @param date1
     * @param date2
     * @return
     */
    public int[] getDateDif(Date date1, Date date2) {
        int[] monthDay = { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        Calendar fromDate;
        Calendar toDate;
        int increment = 0;
        int[] ageDiffArr = new int[3];
        int year;
        int month;
        int day;
        Calendar d1 = new GregorianCalendar().getInstance();
        d1.setTime(date1);
        Calendar d2 = new GregorianCalendar().getInstance();
        d2.setTime(date2);
        if (d1.getTime().getTime() > d2.getTime().getTime()) {
            fromDate = d2;
            toDate = d1;
        } else {
            fromDate = d1;
            toDate = d2;
        }
        if (fromDate.get(Calendar.DAY_OF_MONTH) > toDate.get(Calendar.DAY_OF_MONTH)) {
            increment = monthDay[fromDate.get(Calendar.MONTH)];
        }
        GregorianCalendar cal = new GregorianCalendar();
        boolean isLeapYear = cal.isLeapYear(fromDate.get(Calendar.YEAR));
        if (increment == -1) {
            if (isLeapYear) {
                increment = 29;
            } else {
                increment = 28;
            }
        }
        // DAY CALCULATION
        if (increment != 0) {
            day = (toDate.get(Calendar.DAY_OF_MONTH) + increment) - fromDate.get(Calendar.DAY_OF_MONTH);
            increment = 1;
        } else {
            day = toDate.get(Calendar.DAY_OF_MONTH) - fromDate.get(Calendar.DAY_OF_MONTH);
        }
        // MONTH CALCULATION
        if ((fromDate.get(Calendar.MONTH) + increment) > toDate.get(Calendar.MONTH)) {
            month = (toDate.get(Calendar.MONTH) + 12) - (fromDate.get(Calendar.MONTH) + increment);
            increment = 1;
        } else {
            month = (toDate.get(Calendar.MONTH)) - (fromDate.get(Calendar.MONTH) + increment);
            increment = 0;
        }
        // YEAR CALCULATION
        year = toDate.get(Calendar.YEAR) - (fromDate.get(Calendar.YEAR) + increment);
        ageDiffArr[0] = day;
        ageDiffArr[1] = month;
        ageDiffArr[2] = year;
        return ageDiffArr; // RESULT AS DAY, MONTH AND YEAR in form of Array
    }
    /**
     * @Des  Get Difference Between Two Dates in Days (Total days)
     * @param early
     * @param late
     * @return
     */
    public int daysBetween(Date early, Date late) {
        java.util.Calendar calst = java.util.Calendar.getInstance();
        java.util.Calendar caled = java.util.Calendar.getInstance();
        calst.setTime(early);
        caled.setTime(late);
        // init set time to zero.
        calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
        calst.set(java.util.Calendar.MINUTE, 0);
        calst.set(java.util.Calendar.SECOND, 0);
        caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
        caled.set(java.util.Calendar.MINUTE, 0);
        caled.set(java.util.Calendar.SECOND, 0);
        // get between tow one.
        int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst.getTime().getTime() / 1000)) / 3600 / 24;
        return days;
    }
}



分享到:
评论

相关推荐

    COMPUTE_YEARS_BETWEEN_DATES.doc

    COMPUTE_YEARS_BETWEEN_DATES 是一个用于计算两个日期之间相差年数的函数,在 SAP ABAP(Advanced Business Application Programming)环境中广泛使用。这个功能主要用于处理日期逻辑,尤其是在进行数据处理、报表...

    date_class.zip_between

    This date class consists of lots of function like calculation of age, difference between two dates, Adding number to a date and subtracting and also checking whether the date is valid or not and so on

    between_two_dates_plugin

    获取两个日期之间一个工作日的所有日期 获取前。 两个日期之间的星期一...from between_two_dates_plugin import days_between_two_dates 然后只需简单地使用它即可: days_between_two_dates (start_date, end_date)

    days-between-dates:日期之间有多少天

    日期之间的天数日期之间的间隔天数脚本。 ================== 该脚本将为您提供两个日期之间的天数。 ================== 该脚本正在使用jquery datepicker。

    Date to date.jar

    Date to date.jar is a program compute how many days between two dates

    months-between-dates:日期之间的月份

    日期之间的月份 日期之间有多少个月的脚本。 ================== 该脚本将为您提供两个日期之间的月数。 ================== 该脚本正在使用jquery datepicker。

    C-language-to-calculate-the-number-of-days-between-dates

    本项目标题为“C-language-to-calculate-the-number-of-days-between-dates”,旨在教授如何使用C语言实现这一功能。在进行这样的计算时,我们通常会考虑日期的年份、月份和日,以及可能涉及的闰年规则。 首先,...

    PHP-Dev-Interview-Date-Test:测试要求压缩并作为公司面试过程的一部分发送

    假设 日期将以“YYYY/MM/DD”格式... int $ years , // The number of years between the two dates. int $ months , // The number of years between the two dates. int $ days , // The number of days between

    Swift日期扩展SwiftDateExtension.zip

    //-- Calculating difference between dates: let weeksBetween = NSDate.monthsBetween(date1: someDate, date2: someOtherDate) let monthsBetween = NSDate.weeksBetween(date1: someDate, date2:...

    dates-between:使用生成器获取两个给定日期之间的所有日期

    日期之间 使用获取两个给定日期之间的所有日期。 const startDate = new Date ( '2016-01-01' ) ; const endDate = new ... const datesBetween = require ( 'dates-between' ) ; datesBetween函数接受两个参数,开

    2020春五年级英语下册 Unit 8 Dates of the Month Part B教案 闽教版(三起).doc

    "2020春五年级英语下册 Unit 8 Dates of the Month Part B教案 闽教版(三起).doc" 本资源是一个五年级英语下册的教学计划,主要目标是让学生学习英文单词、句型和文化意识。下面将对该教学计划进行详细的解读和...

    计算两日期之间的天数

    Console.WriteLine("Days between two dates: " + difference.TotalDays); } } ``` 在这个例子中,`date1`和`date2`分别代表了起始和结束日期,`difference`则存储了这两个日期之间的差异。`Console.WriteLine`会...

    计算两天之间的月数.rar

    precise_months = months_between_dates_precise(date1, date2) ``` 这里使用了`relativedelta`函数,它是`dateutil`库的一部分,可以方便地处理日期的加减操作。 需要注意的是,不同的编程语言和库可能有不同的...

    python第16章下载数据课后习题答案.docx

    plt.fill_between(dates, highs, lows, facecolor="blue", alpha=0.15) # 绘制Death Valley数据 dates, highs, lows = [], [], [] get_weather_data("death_valley_2021.csv", dates, highs, lows) plt.plot(dates,...

    Python库 | brymck-dates-0.0.5.tar.gz

    《Python库brymck-dates-0.0.5:深入解析与应用》 Python是一种广泛应用于开发语言,尤其在后端开发中占据重要地位。丰富的第三方库是Python的一大特色,它们为开发者提供了强大的工具集,使得各种复杂任务的处理变...

    miserables-with-dates.zip

    《悲惨世界》是维克多·雨果的一部经典文学作品,而“miserables-with-dates.zip”这个压缩包文件则可能包含了一个与这部作品相关的社交网络分析数据集。从文件名推测,这可能是一个包含人物关系和时间信息的GEXF...

    DirData.rar_Creating_dates_delphi

    这个"DirData.rar_Creating_dates_delphi"资源包含了一个示例,展示了如何使用Delphi来创建按日期命名的目录。 在Delphi中,我们可以利用System.IOUtils单元中的TDirectory类来处理文件和目录操作。TDirectory类...

    EE27 Dates.docx

    1. **`date.get`**:获取日期的某一部分,如年份、月份等。 2. **`date.getFraction`**:获取日期的小数部分。 3. **`date.getRelative`**:获取日期相对于其他日期的相对时间。 4. **`ee.Date.unitRatio`**:计算两...

    ABAP常用日期函数总结.pdf

    15. **HR_99S_INTERVAL_BETWEEN_DATES**:这个函数计算两个日期之间的年数、月数、周数和天数,返回一个结构化的数据,适用于复杂的日期间隔计算。 16. **GET_WEEK_INFO_BASED_ON_DATE**:这个函数根据给定的日期...

    react-native-paper-dates:适用于React Native Paper的平滑,快速的跨平台Material Design日期和时间选择器

    React本机日期 平稳,快速的跨平台Material Design日期选择器和时间... npm install react-native-paper-dates --save 用法 日期选择器 import * as React from 'react' import { Button } from 'react-native-pape

Global site tag (gtag.js) - Google Analytics