How to check if a day lies between a range? - java

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.

Related

Converting String time format of HH:MM:SS (AM/PM) into Seconds

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.

Java Clock Program

I am trying to make a clock program using Java, and I got everything to work properly except I cannot get the program to change the negative values to 0. I also cannot get the program to set the values of hours, minutes, and seconds to 0 if they are out of range. I have a tester program that I have to use and the T1 and T2 clock values are incorrect in my code. T1 should be 0:0:0 and T2 should be 0:0:0 as well. However, when I output my code it comes out as T1 being -3:-21:-30 and T2 is 24:60:60. I know there is something wrong with my code, but I can't find the issue, if anyone would be able to help me that would be greatly appreciated. Below is my code and then the second section is the tester code that I have to use.
public class Clock
{
// instance variables
private int hours;
private int minutes;
private int seconds;
public void setHours(int newHours) {
hours = newHours;
if (hours<0 || hours > 24) {
hours = 0;
}
}
public void setMinutes(int newMinutes) {
minutes = newMinutes;
if (minutes<0 || minutes > 60) {
minutes = 0;
}
}
public void setSeconds(int newSeconds) {
seconds = newSeconds;
if(seconds<0 || seconds > 60) {
seconds = 0;
}
}
/**
* Constructor for objects of class Clock
*/
public Clock(int newHour, int newMinute, int newSecond)
{
if (newHour > -1 || newHour < 24) {
this.hours = newHour;
}
else {
setHours(hours);
}
if (newMinute > -1 || newMinute < 60) {
this.minutes = newMinute;
}
else {
setMinutes(minutes);
}
if (newSecond > -1 || newSecond < 60) {
this.seconds = newSecond;
}
else {
setSeconds(seconds);
}
}
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
public String toString() {
return hours + ":"+minutes+":"+seconds;
}
public void tick() {
seconds = seconds +1;
if(seconds >= 60)
{
minutes ++;
seconds = 0;
}
if(minutes >= 60)
{
hours++;
minutes = 0;
}
if(hours >=24)
{
hours = 0;
}
}
}
The next piece is the tester code.
public class ClockTest {
public static void main(String [] args){
//Create some clocks and print their times
Clock c1 = new Clock(-3,-21,-30);
System.out.println("T1: "+ c1);
c1 = new Clock(24,60,60);
System.out.println("T2: "+ c1);
c1 = new Clock(3,21,30);
System.out.println("T3: "+ c1);
//Tick the clock twice and print its time
c1.tick();
c1.tick();
System.out.println("T4: "+ c1);
c1 = new Clock(3,30,59);
c1.tick();
System.out.println("T5: "+ c1);
c1 = new Clock(3,59,59);
c1.tick();
System.out.println("T6: "+ c1);
c1 = new Clock(23,59,59);
c1.tick();
System.out.println("T7: "+ c1);
c1 = new Clock(0,0,1);
c1.tick();
System.out.println("T8: "+ c1);
c1 = new Clock(1,1,1);
c1.setHours(22);
c1.setMinutes(30);
c1.setSeconds(35);
System.out.println("T9: "+ c1);
System.out.println("T10: " + c1.getHours() + ":"
+c1.getMinutes() + ":" + c1.getSeconds());
}
}
Your condition is wrong.
When you write this:
if (newHour > -1 || newHour < 24) {
You really mean this:
if (newHour > -1 && newHour < 24) {
#nicomp is correct and you should also be using >= 24 and 60 instead of >. You might consider changing the constructor for Clock to
public Clock(int newHour, int newMinute, int newSecond) {
setHours(newHour);
setMinutes(newMinute);
setSeconds(newSecond);
}
and then do all of your validation in the set methods, instead of having some validation in the set methods and some in the constructor.

Convert given time in String format to seconds in Android

Suppose time is given in MM:SS(ex- 02:30) OR HH:MM:SS in String format.how can we convert this time to second.
In your case, using your example you could use something like the following:
String time = "02:30"; //mm:ss
String[] units = time.split(":"); //will break the string up into an array
int minutes = Integer.parseInt(units[0]); //first element
int seconds = Integer.parseInt(units[1]); //second element
int duration = 60 * minutes + seconds; //add up our values
If you want to include hours just modify the code above and multiply hours by 3600 which is the number of seconds in an hour.
public class TimeToSeconds {
// given: mm:ss or hh:mm:ss or hhh:mm:ss, return number of seconds.
// bad input throws NumberFormatException.
// bad includes: "", null, :50, 5:-4
public static long parseTime(String str) throws NumberFormatException {
if (str == null)
throw new NumberFormatException("parseTimeString null str");
if (str.isEmpty())
throw new NumberFormatException("parseTimeString empty str");
int h = 0;
int m, s;
String units[] = str.split(":");
assert (units.length == 2 || units.length == 3);
switch (units.length) {
case 2:
// mm:ss
m = Integer.parseInt(units[0]);
s = Integer.parseInt(units[1]);
break;
case 3:
// hh:mm:ss
h = Integer.parseInt(units[0]);
m = Integer.parseInt(units[1]);
s = Integer.parseInt(units[2]);
break;
default:
throw new NumberFormatException("parseTimeString failed:" + str);
}
if (m<0 || m>60 || s<0 || s>60 || h<0)
throw new NumberFormatException("parseTimeString range error:" + str);
return h * 3600 + m * 60 + s;
}
// given time string (hours:minutes:seconds, or mm:ss, return number of seconds.
public static long parseTimeStringToSeconds(String str) {
try {
return parseTime(str);
} catch (NumberFormatException nfe) {
return 0;
}
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class TimeToSecondsTest {
#Test
public void parseTimeStringToSeconds() {
assertEquals(TimeToSeconds.parseTimeStringToSeconds("1:00"), 60);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("00:55"), 55);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("5:55"), 5 * 60 + 55);
assertEquals(TimeToSeconds.parseTimeStringToSeconds(""), 0);
assertEquals(TimeToSeconds.parseTimeStringToSeconds("6:01:05"), 6 * 3600 + 1*60 + 5);
}
#Test
public void parseTime() {
// make sure all these tests fail.
String fails[] = {null, "", "abc", ":::", "A:B:C", "1:2:3:4", "1:99", "1:99:05", ":50", "-4:32", "-99:-2:4", "2.2:30"};
for (String t: fails)
{
try {
long seconds = TimeToSeconds.parseTime(t);
assertFalse("FAIL: Expected failure:"+t+" got "+seconds, true);
} catch (NumberFormatException nfe)
{
assertNotNull(nfe);
assertTrue(nfe instanceof NumberFormatException);
// expected this nfe.
}
}
}
}
int v = 0;
for (var x: t.split(":")) {
v = v * 60 + new Byte(x);
}
This snippet should support HH:MM:SS (v would result in seconds) or HH:MM (v would be in minutes)
try this
hours = totalSecs / 3600;
minutes = (totalSecs % 3600) / 60;
seconds = totalSecs % 60;
timeString = String.format("%02d",seconds);
private static final String TIME_FORMAT = "hh:mm a";//give whatever format you want.
//Function calling
long timeInMillis = TimeUtils.getCurrentTimeInMillis("04:21 PM");
long seconds = timeInMillis/1000;
//Util Function
public static long getCurrentTimeInMillis(String time) {
SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
// sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //getting exact milliseconds at GMT
// sdf.setTimeZone(TimeZone.getDefault());
Date date = null;
try {
date = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return date.getTime();
}
I have written an extension function in Kotlin for converting String to seconds
fun String?.converTimeToSeconds(): Int {
if (this.isNullOrEmpty().not()) {
val units = this?.split(":")?.toTypedArray()
if (units?.isNotEmpty() == true && units.size >= 3) {
val hours = units[0].toInt()
val minutes = units[1].toInt()
val seconds = units[2].toInt()
return (3660 * hours) + (60 * minutes) + seconds
}
}
return 0
}

How to sum minutes in array if their format is string?

I have an string array that includes some minutes like "00:05", "00:30", "00:25" etc. I want to sum the values as time format? Can anyone help me how do I do this?
Total time in minutes:
int sum = 0;
final String[] mins = new String[] { "00:05", "00:30", "00:25" };
for (String str : mins) {
String[] parts = str.split(":");
sum += Integer.parseInt(parts[1]);
}
System.out.println(sum);
You don't specify exactly how you want this output formatted.
If there may be hour elements as well, then replace the second line of the loop with this:
sum += (Integer.parseInt(parts[0]) * 60) + Integer.parseInt(parts[1]);
I'll go for quick and dirty
Split each String on the ":"
Convert both parts to integer
Multiply the first time by 60 to convert hours to minutes, and add the second part
Do this for each value in your array, and count them together
This results in the total time in minutes, which you can convert to whatever format you like
You could substring it, and then call Integer.parseInt on the result. For the hours part, do the same and multiply it by 60.
Split the strings on ':', pars the values as ints and add 'em up.
this is my suggestion. Neither compiled, ran, tested, nor guaranteed.
long seconds = 0;
for ( String min : minutes )
{
seconds += Integer.parseInt(min.substring(0,1))*60 + Integer.parseInt(min.substring(3,4));
}
return new Date ( seconds / 1000 ) ;
An object oriented approach:
public static TimeAcumm sum(final String[] times) {
final TimeAcumm c = new TimeAcumm();
for (final String time : times) {
c.incrementFromFormattedString(time);
}
return c;
}
public class TimeAcumm {
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
public void incrementFromFormattedString(final String time) {
final String[] parts = time.split(":");
this.minutes += Integer.parseInt(parts[0]);
this.seconds += Integer.parseInt(parts[1]);
validate();
}
private void validate() {
if (this.minutes > 59) {
this.hours++;
this.minutes -= 60;
}
if (this.seconds > 59) {
this.minutes++;
this.seconds -= 60;
}
}
#Override
public String toString() {
final String s = hours + "H:" + minutes + "M:" + seconds + "S";
return s;
}
}

How can I calculate a time difference in Java?

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);

Categories

Resources