So I have this assignment that is asking us to take in a String format of time in the order of HH:MM:SSAM or HH:SS:MMPM. The constraint is that it cannot run if it is in wrong format, let it be missing any form of the AM or PM, missing a number, or if it is in 24 Hour Format.
I have the whole idea down, however for my statements, it is giving me the error of:
bad operand types for binary operator '>'
incomparable types: String and int
Did I convert them improperly or am I doing something else wrong?
public static void main(String args[]) {
//Test Methods
String fullTime1 = "03:21:36AM";
secondsAfterMidnight(fullTime1);
}
public static int secondsAfterMidnight(String time) {
String[] units = time.split(":");
int hours = Integer.parseInt(units[0]);
int minutes = Integer.parseInt(units[1]);
int seconds = Integer.parseInt(units[2]);
int totalSeconds = 0;
if (units[0] > 12 || units[1] > 59 || units[2] > 59) { //1st Error applies to these three, units[0] > 12 units[1] > 59 units[2] > 59
return -1;
} else if (time.equalsIgnoreCase("AM") || time.equalsIgnoreCase("PM")) {
totalSeconds = (hours * 3600) + (minutes * 60) + (seconds);
} else if (time.equalsIgnoreCase("AM") && units[0] == 12) { //2nd Error applies to this units[0] == 12
totalSeconds = (minutes * 60) + (seconds);
} else {
return -1;
}
return totalSeconds;
}
You have already parsed the String values and saved them in the variables hours , minutes, seconds. Then you can use those for the check in the if.
Also the presence of AM?PM in the Integer.parseInt() will cause NumberFormatException to avoid it remove the String part from the number by using regex.
Also for checking the presence of AM/PM you can use String.contains.
Please check the reformatted code below:
public static int secondsAfterMidnight(String time) {
String[] units = time.split(":");
int hours = Integer.parseInt(units[0]);
int minutes = Integer.parseInt(units[1]);
int seconds = Integer.parseInt(units[2].replaceAll("[^0-9]", ""));
int totalSeconds = 0;
if (hours > 12 || minutes > 59 || seconds > 59) {
return -1;
} else if (time.contains("AM") || time.contains("PM")) {
totalSeconds = (hours * 3600) + (minutes * 60) + (seconds);
} else if (time.contains("AM") && hours == 12) {
totalSeconds = (minutes * 60) + (seconds);
} else {
return -1;
}
return totalSeconds;
}
Please note that even though you have converted the String to int, you are still comparing String with int. There would also be a RuntimeException when you do this:
int seconds = Integer.parseInt(units[2]);
As units[2] will contain 36AM. So you should be using substring() to remove the "AM/PM" part.
units is of type String and you are trying to compare it with an int hence the compile time error.
You need to convert the String to an int and then compare it, as shown below :
Integer.parseInt(units[0]) > 12
so on and so forth.
Also rather than re-inventing the wheel, you can make use of the already existing java-8's LocalTime to find the number of seconds for a particular time:
public static int secondsAfterMidnight(String time) {
LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ofPattern("hh:mm:ss a"));
return localTime.toSecondOfDay();
}
I haven't verified your logic to calculate the seconds, but this code has corrections:
public static int secondsAfterMidnight(String time) {
String[] units = time.split(":");
int hours = Integer.parseInt(units[0]);
int minutes = Integer.parseInt(units[1]);
int seconds = 0;
String amPm = "";
if ( units[2].contains("AM") || units[2].contains("PM") ||
units[2].contains("am") || units[2].contains("pm") ) {
seconds = Integer.parseInt(units[2].substring(0, 2));
amPm = units[2].substring(2);
}
else {
seconds = Integer.parseInt(units[2]);
}
int totalSeconds = 0;
if (hours > 12 || minutes > 59 || seconds > 59) {
return -1;
} else if (amPm.equalsIgnoreCase("AM") || amPm.equalsIgnoreCase("PM")) {
totalSeconds = (hours * 3600) + (minutes * 60) + (seconds);
} else if (amPm.equalsIgnoreCase("AM") && hours == 12) {
totalSeconds = (minutes * 60) + (seconds);
} else {
return -1;
}
return totalSeconds;
}
java.time
static DateTimeFormatter timeFormatter
= DateTimeFormatter.ofPattern("HH:mm:ssa", Locale.ENGLISH);
public static int secondsAfterMidnight(String time) {
try {
return LocalTime.parse(time, timeFormatter).get(ChronoField.SECOND_OF_DAY);
} catch (DateTimeParseException dtpe) {
return -1;
}
}
Let’s try it out using the test code from your question:
String fullTime1 = "03:21:36AM";
System.out.println(secondsAfterMidnight(fullTime1));
12096
This is the recommended way for production code.
Only if you are doing an exercise training string manipulation, you should use one of the other answers.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I have a start date and end date in database like below.
start date:01/06/2014 end date:30/06/2014
start date:01/07/2014 end date:30/09/2014
start date:01/10/2014 end date:31/03/2015
if i enter the date range
start date 02/06/2014 end date 01/02/2015
the output has to be.
28 days, in 1st slab date range
2 months, 29 days, in 2nd slab date range
4 months in 3rd slab date range
how to achieve this in java.
Thanks in advance.
This question is difficult to answer accurately. I believe this is what you really want,
// get the minimum of any number of dates.
private static Date getMinimum(Date... dates) {
if (dates == null)
return null;
Date min = dates[0];
for (Date d : dates) {
if (d.compareTo(min) < 0) {
min = d;
}
}
return min;
}
// get the maximum of any number of dates.
private static Date getMaximum(Date... dates) {
if (dates == null)
return null;
Date max = dates[0];
for (Date d : dates) {
if (d.compareTo(max) > 0) {
max = d;
}
}
return max;
}
public static String getDateDiff(Date startDate,
Date endDate) {
StringBuilder sb = new StringBuilder();
Calendar start = Calendar.getInstance();
start.setTime(getMinimum(startDate, endDate));
Calendar end = Calendar.getInstance();
end.setTime(getMaximum(startDate, endDate));
if (start.compareTo(end) < 0) {
int monthCount = 0;
int dayCount = 0;
while (start.compareTo(end) < 0) {
start.add(Calendar.MONTH, 1);
if (start.compareTo(end) < 0) {
monthCount++;
}
}
start = Calendar.getInstance();
start.setTime(getMinimum(startDate, endDate));
start.add(Calendar.MONTH, monthCount);
while (start.compareTo(end) < 0) {
start.add(Calendar.DAY_OF_MONTH, 1);
if (start.compareTo(end) < 0) {
dayCount++;
}
}
if (monthCount > 0) {
sb.append(String.format("%d months",
monthCount));
}
if (dayCount > 0) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(String.format("%d days", dayCount));
}
} else {
sb.append("0 days");
}
return sb.toString();
}
public static void main(String[] args) {
String[] input = { "01/06/2014-30/06/2014", //
"01/07/2014-30/09/2014", //
"01/10/2014-31/03/2015", //
"02/06/2014-01/02/2015", };
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
for (String str : input) {
String sArr[] = str.split("-");
try {
Date start = df.parse(sArr[0]);
Date end = df.parse(sArr[1]);
System.out.printf("start: %s, end: %s - diff: %s\n", sArr[0],
sArr[1], getDateDiff(start, end));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The output is
start: 01/06/2014, end: 30/06/2014 - diff: 28 days
start: 01/07/2014, end: 30/09/2014 - diff: 2 months, 28 days
start: 01/10/2014, end: 31/03/2015 - diff: 5 months, 29 days
start: 02/06/2014, end: 01/02/2015 - diff: 7 months, 29 days
Please check whether below code is helpful. I am using this.
public String getDifference(Date date1, Date date2){
long difference = date2.getTime() - date1.getTime();
long diffDays = difference / (24 * 60 * 60 * 1000);
return (diffDays/30)+" months and "+(diffDays%30)+" days";
}
public int monthsBetweenDates(Date startDate, Date endDate){
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
int monthsBetween = 0;
int dateDiff = end.get(Calendar.DAY_OF_MONTH)-start.get(Calendar.DAY_OF_MONTH);
if(dateDiff<0) {
int borrrow = end.getActualMaximum(Calendar.DAY_OF_MONTH);
dateDiff = (end.get(Calendar.DAY_OF_MONTH)+borrrow)-start.get(Calendar.DAY_OF_MONTH);
monthsBetween--;
if(dateDiff>0) {
monthsBetween++;
}
}
else {
monthsBetween++;
}
monthsBetween += end.get(Calendar.MONTH)-start.get(Calendar.MONTH);
monthsBetween += (end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;
return monthsBetween;
}
I have a job which runs from a given day to a certain day of week . For eg (Monday to Saturday).
I was able to cover the case when stopday > starday for eg-startday->Monday stopDay->Saturday
but when the range changes to something like Wednesday to Monday , I am not able to cover this case.
private boolean isNotWindow(DateTime todayDate) {
final int hr = 3600;
final int min = 60;
int stopDay =
Integer.parseInt(ShipmentTrackingEmailProperties.getInstance().getProperty(
ShipmentTrackingEmailProperties.SHIPMENT_EMAIL_STOP_DAY));
int startDay =
Integer.parseInt(ShipmentTrackingEmailProperties.getInstance().getProperty(
ShipmentTrackingEmailProperties.SHIPMENT_EMAIL_START_DAY));
if(stopDay<startDay)
{
//Not able to figure out??????
}
if (todayDate.getDayOfWeek() >= stopDay) {
String stopTime =
ShipmentTrackingEmailProperties.getInstance().getProperty(ShipmentTrackingEmailProperties.SHIPMENT_EMAIL_STOP_TIME);
String[] array = stopTime.split(":");
System.out.println(array[0] + " " + array[1] + " " + array[2]);
int hh = Integer.parseInt(array[0]);
int mm = Integer.parseInt(array[1]);
int ss = Integer.parseInt(array[2]);
int tSec = todayDate.getHourOfDay() * hr + todayDate.getMinuteOfDay() * min + todayDate.getSecondOfDay();
int sSec = hh * hr + mm * min + ss;
if (tSec > sSec) {
return true;
}
}
if (todayDate.getDayOfWeek() <= startDay) {
String startTime =
ShipmentTrackingEmailProperties.getInstance().getProperty(ShipmentTrackingEmailProperties.SHIPMENT_EMAIL_START_TIME);
String[] array = startTime.split(":");
int hh = Integer.parseInt(array[0]);
int mm = Integer.parseInt(array[1]);
int ss = Integer.parseInt(array[2]);
int tSec = todayDate.getHourOfDay() * hr + todayDate.getMinuteOfDay() * min + todayDate.getSecondOfDay();
int sSec = hh * hr + mm * min + ss;
if (tSec <= sSec) {
LOG.info("Not a valid day to send mail ." + todayDate.getDayOfWeek());
return true;
}
}
LOG.info("Valid day to send mail ." + todayDate.getDayOfWeek());
return false;
}
This function returns true if the day does not fall in a range.So how to cover the case when
stopDay < startDay
You need:
if startday<stopday then
if the day is in the interval (startday,stopday) then OK
else NotOk
else
if the day is not in the interval (startday,stopday) then OK
else NotOk
It could be much easier done as:
If((day-startday)*(stopday-day)*(stopday-startday)>=0) then OK
else NotOk
You can use this function to check for the day in range
private static boolean inRange(int startDay, int stopDay, int checkMe) {
if(startDay==stopDay) {
if(startDay==checkMe){
return true;
} else {
return false;
}
}
while(startDay!=stopDay) {
if(startDay==checkMe || stopDay==checkMe) {
return true;
}
if(startDay==7) {
startDay =0;
}
startDay++;
}
return false;
}
Hope it helps.
I have read a lot of answers here regarding getting the totalTime. I tried to apply this code that I found to my code:
long secs = (dateFormatter.format(now2) - dateFormatter.format(now1)) / 1000;
int hours = secs / 3600;
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;
My code:
public void actionPerformed(ActionEvent e)
{
LogicalChecker lc = new LogicalChecker();
Date now1 = new Date();
Date now2 = new Date();
cobadatabase cb = new cobadatabase(studNumTF.getText());
String output;
if(e.getActionCommand() == "Log In")
{
if(station == 0)
{
lc.StationCheck(0);
}
else if(seatOccupied[station-1] == true)
{
lc.StationCheck(2);
}
else if(!studNumTF.getText().equals(cb.getStudentNumber()))
{
studNumTF.setText("");
lc.StationCheck(3);
}
else
{
seatOccupied[station-1] = true;
Aid[station-1].setText(cb.getStudentNumber());
Afirstname[station-1].setText(cb.getFirstName());
Alastname[station-1].setText(cb.getLastName());
seat[station-1].setBackground(Color.red);
Atime[station-1].setText(dateFormatter.format(now1));
occupiedSeatCounter++;
}
}
if(e.getActionCommand() == "Log Out")
{
if(station == 0)
{
lc.StationCheck(0);
}
else if(Aid[station-1].getText() == "Vacant Station")
{
lc.StationCheck(1);
}
else
{
Aid[station-1].setText("Vacant Station");
Afirstname[station-1].setText("---------");
Alastname[station-1].setText("---------");
seat[station-1].setBackground(Color.green);
Atime[station-1].setText("00:00:00");
seatOccupied[station-1] = false;
studNumTF.setText("");
output = "Time Check-Out "+dateFormatter.format(now2)+"\n Total Time: ";
JOptionPane.showMessageDialog(null,output, "Check-Out.",JOptionPane.INFORMATION_MESSAGE);
}
}
}
But it gives an error that says operator cannot be applied to java.lang.String. I do not know what to do to get its total time and display it to the JOptionPane that I have created. I really need help.
Your issue is here: dateFormatter.format(now2) - dateFormatter.format(now1) because like #Luiggi said the format returns a string. You should do something like: now2.getTime() - now1.getTime() to get the difference in milliseconds.
I want to subtract two time periods say 16:00:00 from 19:00:00. Is there any Java function for this? The results can be in milliseconds, seconds, or minutes.
Java 8 has a cleaner solution - Instant and Duration
Example:
import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");
String time1 = "16:00:00";
String time2 = "19:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
Difference is in milliseconds.
I modified sfaizs post.
To get pretty timing differences, then
// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
Java 8
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1= LocalDateTime.parse("2014-11-25 19:00:00", formatter);
LocalDateTime dateTime2= LocalDateTime.parse("2014-11-25 16:00:00", formatter);
long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
long diffInSeconds = java.time.Duration.between(dateTime1, dateTime2).getSeconds();
long diffInMinutes = java.time.Duration.between(dateTime1, dateTime2).toMinutes();
Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract.
Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.
Ah, give the above poster (genesiss) his due credit, code's always handy ;)
Though, you now have an explanation as well :)
import java.util.Date;
...
Date d1 = new Date();
...
...
Date d2 = new Date();
System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds.
System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds.
and, to show in a nicer format, you can use:
DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###");
System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000));
Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.
Advanced Java 8 libraries.
ChronoUnit for Differences.
ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.
LocalTime one = LocalTime.of(5,15);
LocalTime two = LocalTime.of(6,30);
LocalDate date = LocalDate.of(2019, 1, 29);
System.out.println(ChronoUnit.HOURS.between(one, two)); //1
System.out.println(ChronoUnit.MINUTES.between(one, two)); //75
System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException
First example shows that between truncates rather than rounds.
The second shows how easy it is to count different units.
And the last example reminds us that we should not mess up with dates and times in Java :)
public class timeDifference {
public static void main(String[] args) {
try {
Date startTime = Calendar.getInstance().getTime();
Thread.sleep(10000);
Date endTime = Calendar.getInstance().getTime();
long difference = endTime.getTime() - startTime.getTime();
long differenceSeconds = difference / 1000 % 60;
long differenceMinutes = difference / (60 * 1000) % 60;
long differenceHours = difference / (60 * 60 * 1000) % 24;
long differenceDays = difference / (24 * 60 * 60 * 1000);
System.out.println(differenceDays + " days, ");
System.out.println(differenceHours + " hours, ");
System.out.println(differenceMinutes + " minutes, ");
System.out.println(differenceSeconds + " seconds.");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I found this cleaner.
Date start = new Date();
//Waiting for 10 seconds
Thread.sleep(10000);
Date end = new Date();
long diff = end.getTime() - start.getTime();
String TimeTaken = String.format("[%s] hours : [%s] mins : [%s] secs",
Long.toString(TimeUnit.MILLISECONDS.toHours(diff)),
TimeUnit.MILLISECONDS.toMinutes(diff),
TimeUnit.MILLISECONDS.toSeconds(diff));
System.out.println(String.format("Time taken %s", TimeTaken));
Output
Time taken [0] hours : [0] mins : [10] secs
The painful way is to convert to millis and do the subtraction and then back to whatever seconds or so you want. The better way is to use JodaTime.
String start = "12:00:00";
String end = "02:05:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(start);
Date date2 = format.parse(end);
long difference = date2.getTime() - date1.getTime();
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(difference);
if(minutes<0)minutes += 1440;
Now minutes will be the correct duration between two time (in minute).
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
String time1 = "12:00:00";
String time2 = "12:01:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference/1000);
}
}
It throws exception handles parsing exceptions.
This can be easily done using Java 8 LocalTime;
String time1 = "16:00:00";
String time2 = "19:00:00";
long seconds = Duration.between(LocalTime.parse(time1), LocalTime.parse(time2)).getSeconds()
Duration also supports toMillis(), toMinutes() which can be used in place of getSeconds() to get milliseconds or minutes
Аlternative option if time from different days is taken, for example: 22:00 and 01:55.
public static long getDiffTime(Date date1, Date date2){
if (date2.getTime() - date1.getTime() < 0) {// if for example date1 = 22:00, date2 = 01:55.
Calendar c = Calendar.getInstance();
c.setTime(date2);
c.add(Calendar.DATE, 1);
date2 = c.getTime();
} //else for example date1 = 01:55, date2 = 03:55.
long ms = date2.getTime() - date1.getTime();
//235 minutes ~ 4 hours for (22:00 -- 01:55).
//120 minutes ~ 2 hours for (01:55 -- 03:55).
return TimeUnit.MINUTES.convert(ms, TimeUnit.MILLISECONDS);
}
Try this:
public String timeDifference8(String startTime, String endTime) {
LocalTime initialTime = LocalTime.parse(startTime);
LocalTime finalTime =LocalTime.parse(endTime);
StringJoiner joiner = new StringJoiner(":");
long hours = initialTime.until( finalTime, ChronoUnit.HOURS);
initialTime = initialTime.plusHours( hours );
long minutes = initialTime.until(finalTime, ChronoUnit.MINUTES);
initialTime = initialTime.plusMinutes( minutes );
long seconds = initialTime.until( finalTime, ChronoUnit.SECONDS);
joiner.add(String.valueOf(hours));
joiner.add(String.valueOf(minutes));
joiner.add(String.valueOf(seconds));
return joiner.toString();
}
import java.sql.*;
class Time3 {
public static void main(String args[]){
String time1 = "01:03:23";
String time2 = "02:32:00";
long difference ;
Time t1 = Time.valueOf(time1);
Time t2 = Time.valueOf(time2);
if(t2.getTime() >= t1.getTime()){
difference = t2.getTime() - t1.getTime() -19800000;
}
else{
difference = t1.getTime() - t2.getTime() -19800000;
}
java.sql.Time time = new java.sql.Time(difference);
System.out.println(time);
}
}
/*
* Total time calculation.
*/
private void getTotalHours() {
try {
// TODO Auto-generated method stub
if (tfTimeIn.getValue() != null && tfTimeOut.getValue() != null) {
Long min1 = tfTimeOut.getMinutesValue();
Long min2 = tfTimeIn.getMinutesValue();
Long hr1 = tfTimeOut.getHoursValue();
Long hr2 = tfTimeIn.getHoursValue();
Long hrsTotal = new Long("0");
Long minTotal = new Long("0");
if ((hr2 - hr1) == 1) {
hrsTotal = (long) 1;
if (min1 != 0 && min2 == 0) {
minTotal = (long) 60 - min1;
} else if (min1 == 0 && min2 != 0) {
minTotal = min2;
} else if (min1 != 0 && min2 != 0) {
minTotal = min2;
Long minOne = (long) 60 - min1;
Long minTwo = min2;
minTotal = minOne + minTwo;
}
if (minTotal >= 60) {
hrsTotal++;
minTotal = minTotal % 60;
}
} else if ((hr2 - hr1) > 0) {
hrsTotal = (hr2 - hr1);
if (min1 != 0 && min2 == 0) {
minTotal = (long) 60 - min1;
} else if (min1 == 0 && min2 != 0) {
minTotal = min2;
} else if (min1 != 0 && min2 != 0) {
minTotal = min2;
Long minOne = (long) 60 - min1;
Long minTwo = min2;
minTotal = minOne + minTwo;
}
if (minTotal >= 60) {
minTotal = minTotal % 60;
}
} else if ((hr2 - hr1) == 0) {
if (min1 != 0 || min2 != 0) {
if (min2 > min1) {
hrsTotal = (long) 0;
minTotal = min2 - min1;
} else {
Notification.show("Enter A Valid Time");
tfTotalTime.setValue("00.00");
}
}
} else {
Notification.show("Enter A Valid Time");
tfTotalTime.setValue("00.00");
}
String hrsTotalString = hrsTotal.toString();
String minTotalString = minTotal.toString();
if (hrsTotalString.trim().length() == 1) {
hrsTotalString = "0" + hrsTotalString;
}
if (minTotalString.trim().length() == 1) {
minTotalString = "0" + minTotalString;
}
tfTotalTime.setValue(hrsTotalString + ":" + minTotalString);
} else {
tfTotalTime.setValue("00.00");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
class TimeCalculator
{
String updateTime;
public TimeCalculator(String time)
{
// Time should be in 24 hours format like 15/06/2016 17:39:20
this.updateTime = time;
}
public String getTimeDifference()
{
String td = null;
// Get Current Time
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date currentDate = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(currentDate);
int c_year = calendar.get(Calendar.YEAR);
int c_month = calendar.get(Calendar.MONTH) + 1;
int c_day = calendar.get(Calendar.DAY_OF_MONTH);
// Get Editing Time
Date edit_date = sdf.parse(updateTime);
Calendar edit_calendar = new GregorianCalendar();
edit_calendar.setTime(edit_date);
int e_year = edit_calendar.get(Calendar.YEAR);
int e_month = edit_calendar.get(Calendar.MONTH) + 1;
int e_day = edit_calendar.get(Calendar.DAY_OF_MONTH);
if(e_year == c_year && e_month == c_month && e_day == c_day)
{
int c_hours = calendar.get(Calendar.HOUR_OF_DAY);
int c_minutes = calendar.get(Calendar.MINUTE);
int c_seconds = calendar.get(Calendar.SECOND);
int e_hours = edit_calendar.get(Calendar.HOUR_OF_DAY);
int e_minutes = edit_calendar.get(Calendar.MINUTE);
int e_seconds = edit_calendar.get(Calendar.SECOND);
if(c_hours == e_hours && c_minutes == e_minutes && c_seconds == e_seconds)
{
td = "just now";
return td;
}
else if(c_hours == e_hours && c_minutes == e_minutes)
{
int d_seconds = c_seconds-e_seconds;
td = String.valueOf(d_seconds);
td = td + " seconds ago";
return td;
}
else if(c_hours == e_hours && c_minutes != e_minutes)
{
int d_minutes = c_minutes-e_minutes;
int d_seconds;
if(c_seconds>e_seconds)
{
d_seconds = c_seconds-e_seconds;
}
else
{
d_seconds = e_seconds-c_seconds;
}
td = "00:" + String.valueOf(d_minutes) + ":" + String.valueOf(d_seconds) + " ago";
return td;
}
else
{
int d_minutes, d_seconds, d_hours;
d_hours = c_hours-e_hours;
if(c_minutes>e_minutes)
{
d_minutes = c_minutes - e_minutes;
}
else
{
d_minutes = e_minutes - c_minutes;
}
if(c_seconds>e_seconds)
{
d_seconds = c_seconds - e_seconds;
}
else
{
d_seconds = e_seconds - c_seconds;
}
td = String.valueOf(d_hours) + ":" + String.valueOf(d_minutes) + ":" + String.valueOf(d_seconds) + " ago";
return td;
}
}
else if(e_year == c_year && e_month == c_month && c_day == e_day+1)
{
td = "yesterday";
return td;
}
else
{
td = updateTime;
return td;
}
}
}
using Instant
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
Instant end = Instant.parse("2017-10-04T11:35:31.00Z");
long duration = Duration.between(start, end).toMillis();
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)*60;
String time = String.format("%02d hours, %02d min, %02d sec",
TimeUnit.MILLISECONDS.toHours(duration),
TimeUnit.MILLISECONDS.toMinutes(duration) - TimeUnit.MILLISECONDS.toHours(duration) * 60,
TimeUnit.MILLISECONDS.toSeconds(duration) - minutes);
;
System.out.println("time = " + time);