Currently I have a function which can take the start time and end time of one day, and calculate the difference between the two, giving me the hours worked in a day. What I would like to do is be able to get the hours worked for 7 days, and return a grand total, while remaining with the display format (HH:mm).
My function for a single day's total:
Period p = new Period(this.startTime[dayIndex], this.endTime[dayIndex]);
long hours = p.getHours();
long minutes = p.getMinutes();
String format = String.format("%%0%dd", 2);//Ensures that the minutes will always display as two digits.
return Long.toString(hours)+":"+String.format(format, minutes);
this.startTime[] & this.endTime[] are both arrays of DateTime objects.
Any suggestions?
You'll need something to hold a week's worth of days, and call your function once for each day.
But that means you'll want to refactor so that your calculator method doesn't format as a string, but instead returns a numeric value, so you can easily add them together.
Another simple solution:
Here is a method that receives separate the hours and minutes.The parameters are:
Start Hour
Start Minutes
End Hour
End Minutes
first, calculate the difference between hours and minutes separate:
int hours = pEndHour - pStartHour;
int minutes = ((60 - pStartMinutes) + pEndMinutes) - 60;
then, validates if the value of "minutes" variable is negative:
// If so, the "negative" value of minutes is our remnant to the next hour
if (minutes < 0) {
hours--;
minutes = 60 + minutes ;
}
Finally you can print the period of time in the hour format:
String format = String.format("%%0%dd", 2);
System.out.println( "*** " + hours + " : " + minutes);
That's all.
Solution I ended with for those interested
Period[] p=new Period[7];
long hours = 0;
long minutes =0;
for(int x=0; x<=this.daysEntered;x++)
{
p[x] = new Period(this.startTime[x], this.endTime[x]);
hours += p[x].getHours();
minutes += p[x].getMinutes();
}
hours += minutes/60;
minutes=minutes%60;
String format = String.format("%%0%dd", 2);
return Long.toString(hours)+":"+String.format(format, minutes);
Related
I'm trying to compare a duration to an integer representing minutes (so another duration) in order to find out if it's a longer or shorter time. I'm trying to use compareTo(Duration duration) method but I can't use an int as parameter. How would I transform that int (minutes) into Duration?
You can create a duration in minutes with the ofMinutes static method. So, as a silly example
int compareDurations(Duration d) {
int myMinutes = 5;
Duration durationInMinutes = Duration.ofMinutes(myMinutes);
return d.compareTo(durationMinutes);
}
I always find code involving compareTo() hard to read. Therefore for most purposes I would prefer to do it the other way around: convert your Duration to minutes and compare using plain < or >.
int minutes = 7;
Duration dur = Duration.ofMinutes(7).plusSeconds(30);
if (minutes > dur.toMinutes()) {
System.out.println("The minutes are longer");
} else {
System.out.println("The minutes are shorter or the same");
}
Output:
The minutes are shorter or the same
If you need to know whether the minutes are strictly shorter, the code will be a bit longer, of course (no joke intended). One way does involve converting the minutes to a Duration in some cases:
if (minutes > dur.toMinutes()) {
System.out.println("The minutes are longer");
} else if (Duration.ofMinutes(minutes).equals(dur)) {
System.out.println("The minutes are the same");
} else {
System.out.println("The minutes are shorter");
}
The minutes are shorter
I really wish the Duration class had had methods isLonger() and isShorter() (even though the names just suggested may not be quite clear when it comes to negative durations). Then I would have recommended converting the minutes to a Duration too as in the accepted answer.
One way, with Duration:
Duration duration = Duration.of(10, ChronoUnit.SECONDS);
int seconds = 5;
System.out.println(duration.getSeconds() - seconds);
Note, that ChronoUnit has a lot of useful constant members, like MINUTES, DAYS, WEEKS, CENTURIES, etc.
Another way, with LocalTime:
LocalTime localTime = LocalTime.of(0, 0, 15); //hh-mm-ss
int seconds = 5;
System.out.println(localTime.getSecond() - seconds);
This question already has answers here:
Java 8: Difference between two LocalDateTime in multiple units
(11 answers)
Closed 2 years ago.
I decided to give myself a challenge on Java that implements this question's achievement.
The things I have to do is get LocalDateTime, convert the same code from the linked question's answers, then receiving a string from the function.
Here's what I've done so far:
public static String relTime(LocalDateTime now)
{
// accepted answer converted to Java
const int min = 60 * SECOND;
const int hour = 60 * MINUTE;
const int day = 24 * HOUR;
const int mon = 30 * DAY;
// still don't know how to convert this method
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
The only problem that I should encounter is from var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);.
Although I read 2 questions from Stack Overflow finding equivalents of TimeSpan and Ticks, I baely have any ideas how to properly convert the line of code. Also, I have to get a double which will need math.abs() to get TotalSeconds which I can't really find a proper way to deal with either, but I did find ZoneOffset.ofTotalSeconds and still don't know how to deal with it.
So how can I convert this properly?
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
You need to gain a deeper understanding of what this method actually does. Literally translating code from C# to Java won't give you a good solution and gets you stuck on language-specific details.
The two lines basically calculate the (absolute) difference in seconds of a timestamp to the current time. This can be written in Java as follows:
Duration duration = Duration.between(LocalDateTime.now(), timestamp);
long delta = duration.abs().getSeconds();
I'm just addressing your actual question here on how to transform these two lines. The provided snippet is not valid Java code and some parts are missing. delta is the difference in seconds which does not necessarily need to be a double. The argument you pass to your method should be named anything else than now because this is the timestamp you want to compare to the current time inside the method.
You could use SimpleDateFormat to create a nice display format (use something like "HH hours, mm minutes and ss seconds ago" for the format (not sure if this exact example works)). You could also use Instant to get the current time, and you can use Instant.now().minusSeconds(Instant.now().minusSeconds(seconds).getEpochSeconds()) for the time difference (or just use System.currentTimeMillis() and multiply by 1000).
Alternatively, you could use Duration and write a custom display format using getSeconds() and getHours() etc.
I am trying to format a long until days, hours, minutes, seconds and found a method online.
public static String getTime(long time) {
long enlapsed = System.currentTimeMillis() - time;
long days = TimeUnit.MILLISECONDS.toDays(enlapsed);
enlapsed -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(enlapsed);
enlapsed -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(enlapsed);
enlapsed -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(enlapsed);
String result = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
return result.replace("0d ", "").replace("0h ", "").replace("0m ", "").replace("0s ", "");
}
and it was working but now suddenly inputting 4380 is giving 18151d 15h 33m 34s. What did I do wrong?
The method you found online calculates how much time has elapsed between now, and a given timestamp. You can test that this method works going to a site like this, and multiplying the timestamp by 1000 to convert it to milliseconds, and passing that long to getTime.
The timestamp 4380 represents 4380ms after the Java Epoch, which is approximately 1 January 1970, which is about 18000 days ago.
If you want a more recent example, the timestamp 1568312340000 is just a few minutes before I started writing this, and doing System.out.println(getTime(1568312340000L)); gives a smaller duration.
What you seem to want is not to calculate the elapsed time between now and a certain timestamp. You seem to just want to convert an amount of milliseconds to a duration expressed in days, hours, minutes and seconds.
The method works by first calculating the difference in milliseconds between now and the given timestamp, putting the difference into a variable called enlapsed (spelling mistake!) Then it calculates how many days, hours, minutes and seconds goes into enlapsed milliseconds. What you want is everything this method does except the first part where it calculates the difference, so you should delete this line:
long enlapsed = System.currentTimeMillis() - time;
and replace it with:
long enlapsed = time;
because you just want it to directly calculate what duration the time parameter represents.
An input of 4380 to your method would return the time from the epoch minus about 4 seconds. The epoch is 1970-01-01, so 18151 days/365.25 = 49.7 years - which in September of 2019 seems right to me.
I have a string that contain certain hour ex. 14:34, and now I want to calculate the difference between the current hour ex. 21:36-14:34=7 hours 2 minutes (or something like that.) Can someone explain me how can I do that?
It's very easy: You need to separate the string in terms you can add or substract:
String timeString1="12:34";
String timeString2="06:31";
String[] fractions1=timeString1.split(":");
String[] fractions2=timeString2.split(":");
Integer hours1=Integer.parseInt(fractions1[0]);
Integer hours2=Integer.parseInt(fractions2[0]);
Integer minutes1=Integer.parseInt(fractions1[1]);
Integer minutes2=Integer.parseInt(fractions2[1]);
int hourDiff=hours1-hours2;
int minutesDiff=minutes1-minutes2;
if (minutesDiff < 0) {
minutesDiff = 60 + minutesDiff;
hourDiff--;
}
if (hourDiff < 0) {
hourDiff = 24 + hourDiff ;
}
System.out.println("There are " + hourDiff + " and " + minutesDiff + " of difference");
UPDATE:
I'm rereading my answer and I'm surprised is not downvoted. My fault. I wrote it without any IDE check. So, the answer should be minutes1 and 2 for the minutesDiff and obviously and a check to carry the hour difference if the rest of minutes is negative, making minutes (60+minutesDiff). If minutes is negative, rest another hour to the hourDiff. If hours become negative too, make it (24+hourDiff). Now is fixed.
For the sake of fastness, I'm using a custom function. For the sake of scalability, read Nikola Despotoski answer and complete it with this:
System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.println(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
I would start by using the .split method to get the string into its two components (minutes and hours) then I would convert both times into minutes by mutliplying the hours by 60 and then adding the minutes
String s = "14:34";
String[] sArr = s.split(",");
int time = Integer.parseInt(sArr[0]);
time *= 60;
int time2 = Integer.parseInt(sArr[1]);
time = time + time2;
do this for both strings and then subtract one from the other. You can convert back to normal time by using something like this
int hours = 60/time;
int minutes = 60%time;
The answer labeled as correct will not work. It does not account for if the first time is for example 3:17 and the second is 2:25. You end up with 1 hour and -8 minutes!
Problem Statement:
Write a method whatTime, which takes an int, seconds, representing the number of seconds since midnight on some day, and returns a String formatted as "::". Here, represents the number of complete hours since midnight, represents the number of complete minutes since the last complete hour ended, and represents the number of seconds since the last complete minute ended. Each of , , and should be an integer, with no extra leading 0's. Thus, if seconds is 0, you should return "0:0:0", while if seconds is 3661, you should return "1:1:1"
My Algorithm:
Here is how my algorithm is supposed to work for the input 3661:
3661/3600 = 1.016944 -> This means the number of hours is 1
Subtract the total number of hours elapsed i.e. 1.016944-1=0.016944
Multiply this with 60 i.e. 0.016944*60=1.016666 -> The number of minutes elapsed is equal to 1
Subtract the total number of minutes elapsed i.e. 1.01666-1=0.01666. Multiply this with 60. This would yield the number of seconds elapsed.
The output produced however is 1:1:0. I tried to use a print statement and it appears that the value of 'answer3' variable is 0.999 and that is why prints the integer part (0). I tried to use the Math.ceil() function to round up the value and it produces a correct output. However I can only score about 60/250 points when I submit my code (TopCoder SRM 144 Div2) . Any insight for improving the algorithm will be helpful.
public class Time
{
public String whatTime(int seconds)
{
double answer1,answer2,answer3; int H;
answer1=(double)seconds/3600;
H=(int)answer1;
answer2=(double)((answer1-H)*60);
int M=(int)answer2;
answer3=answer2-M;
answer3=(double)answer3*60;
int S=(int)answer3;
String answer=Integer.toString(H);
answer=Integer.toString(H)+":"+Integer.toString(M)+":"+Integer.toString(S);
return answer;
}
}
public String whatTime(int seconds) {
int secondVal = seconds % 60;
int minutes = seconds / 60;
int minuteVal = minutes % 60;
int hours = minutes / 60;
int hourVal = hours % 24;
int daysVal = hours / 24;
String answer = "" + daysVal + ":" + hourVal + ":" + minuteVal + ":" + secondVal;
return answer;
}
Could do the formatting more elegantly, but that's the basic idea.
Avoid floating point values, and work entirely with ints or longs.
You could solve this by working with ints :
3661/3600 = 1.016944 -> This means the number of hours is 1
Subtract the number of hours * 3600 - i.e. 3661-(1*3600) = 61
61/60 = 1.0166666 -> The number of minutes elapsed is equal to 1
Subtract the number of minutes * 60 i.e. 61-(1*60)=1. This yields the number of seconds elapsed.