Find total hours between two Dates

前端 未结 11 1367
抹茶落季
抹茶落季 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,

提交回复
热议问题