Find total hours between two Dates

前端 未结 11 1306
抹茶落季
抹茶落季 2020-11-28 06:00

I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like w

相关标签:
11条回答
  • 2020-11-28 06:43

    Here is the simple method :- Check your Date format,if your date not in this format then change it and pass to this method it will give you a String which is your result. Modify the method as per the requirement.

    private String getDateAsTime(String datePrev) {
            String daysAsTime = "";
            long day = 0, diff = 0;
            String outputPattern = "yyyy:MM:dd HH:mm:ss";
            SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
            Calendar c = Calendar.getInstance();
            String dateCurrent = outputFormat.format(c.getTime());
            try {
               Date  date1 = outputFormat.parse(datePrev);
                Date date2 = outputFormat.parse(dateCurrent);
                diff = date2.getTime() - date1.getTime();
                day = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (day == 0) {
                long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
                if (hour == 0)
                    daysAsTime = String.valueOf(TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS)).concat(" minutes ago");
                else
                    daysAsTime = String.valueOf(hour).concat(" hours ago");
            } else {
                daysAsTime = String.valueOf(day).concat(" days ago");
            }
            return daysAsTime;
        }
    

    Hope this will help,

    0 讨论(0)
  • 2020-11-28 06:48

    Here's simple way:

    private static int hoursDifference(Date date1, Date date2) {
    
        final int MILLI_TO_HOUR = 1000 * 60 * 60;
        return (int) (date1.getTime() - date2.getTime()) / MILLI_TO_HOUR;
    }
    
    0 讨论(0)
  • 2020-11-28 06:51

    java.time.Duration

    I should like to contribute the modern (java 8+) answer. The solutions using Joda-Time are fine. The Joda-Time project is in maintenance mode, so for new code we should not use it. I follow the official recommendation from the Joda-Time project and use java.time, the modern Java date and time API:

        Duration dur = Duration.between(startDate, endDate);
        String result = String.format("%d:%02d", dur.toHours(), dur.toMinutesPart());
        System.out.println(result);
    

    This works if startDate and endDate both have type Instant or OffsetDateTime or ZonedDateTime or LocalDateTime or LocalTime. All of the mentioned types are from java.time package. If starting with LocalDate, call either of the atStartOfDay methods.

    The toMinutesPart methof was introduced in Java 9. If you are using Java 8 (ot ThreeTen Backport), search for java format duration or similar to learn how to format the duration into hours and minutes.

    Two quotes from the Joda-Time home page:

    Users are now asked to migrate to java.time (JSR-310).

    Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

    Links

    • Oracle tutorial: Date Time explaining how to use java.time.
    • Joda-Time home page
    0 讨论(0)
  • 2020-11-28 06:51

    Even though there's already an accepted answer, this is what worked for me using the Joda time library.

    /**
     *
     * @param date1
     * @param date2
     * @return hours between two dates rounded down
     */
    public static int hoursBetween(DateTime date1, DateTime date2) {
        if(date1 == null || date2 == null) return NOT_FOUND;
    
        return Math.abs(Hours.hoursBetween(date1.toLocalDateTime(), date2.toLocalDateTime()).getHours());
    }
    
    0 讨论(0)
  • 2020-11-28 06:52

    for kotlin, you can use below function and get hours between two date

    private val dateFormat: String = "yyyy-MM-dd @ hh:mm a"
    val startDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 12:33 PM")
    val endDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 02:46 PM")
    
    private fun hoursDifference(date1: Date, date2: Date): Int {
        val milliToHour : Long = 1000 * 60 * 60
        return ((date1.time - date2.time) / milliToHour).toInt()
    }
    
    println(hoursDifference(endDate,startDate).toString())
    

    Output: 2

    0 讨论(0)
提交回复
热议问题