I'm working on a project, it's about parking and it contains a database. I have variable timestamp for time/date when car enter the parking, and one also for when the car is on the exit.
I want to get difference in hours (minute after every full hour is a new hour etc. 4 hours and 2 mins are same as 5 hours) so I can calculate price of the service (hours multiply by price per hour).
Help me pls, and thank you in advance
get difference in milliseconds and calculate as below
long timeDiff = endTime.getTime() - startTime.getTime()
int hours = (int)Math.ceil(timeDiff/1000*60*60) //In here we are converting milli seconds difference to hours and then if it is not an exact number we are converting that to the next integer
After obtaining the time value in milliseconds (e.g. using a Date object) use TimeUnit to get the difference in times:
TimeUnit.HOURS.convert(timeOut.getTime()-timeIn.getTime(), TimeUnit.MILLISECONDS);
Related
I am trying to convert code from Python to Java. I need to rewrite the timedelta function in Java. Here is the code in Python:
def timeDate(date):
return (timedelta(seconds=date * 3600 % 86400))
Does anyone have any idea on how to make a function that acts the same?
double hours = 21.37865107050986;
long nanos = Math.round(hours * TimeUnit.HOURS.toNanos(1));
Duration d = Duration.ofNanos(nanos);
// Delete any whole days
d = d.minusDays(d.toDays());
System.out.println(d);
This prints:
PT21H22M43.143853836S
Which means: a duration of 21 hours 22 minutes 43.143853836 seconds.
Assumptions: I understand that you want a duration (the docs you link to say “A timedelta object represents a duration”). I have taken date to be a floating-point number of hours, and your modulo operation lead me to believe that you want the duration modulo 1 day (so 26 hours should come out as a duration of 2 hours).
The Duration class in Java is for durations, hence is the one that you should use. It doesn’t accept a floating point number for creation, so I converted your hours so nanoseconds and rounded to whole number. For the conversion I multiplied by the number of nanoseconds in 1 hour, which I got from the call to TimeUnit (this gives clearer and less error-prone code than multiplying out ourselves).
The code above will tacitly give incorrect results for numerically large numbers of hours, so you should check the range before using it. Up to 2 500 000 hours (100 000 days or nearly 300 years) you should be safe.
Please note: if date was a time of day and not a duration, it’s a completely different story. In this case you should use LocalTime in Java. It’s exactly for a time of day (without date and without time zone).
nanos = nanos % TimeUnit.DAYS.toNanos(1);
LocalTime timeOfDay = LocalTime.ofNanoOfDay(nanos);
System.out.println(timeOfDay);
21:22:43.143853836
Link: Documentation of the Duration class
As far as I know, Java doesn't have a built in DeltaTime function. However you can easily make your own.long startTime;
long delta; public void deltaTime(){ long currentTime = System.currentTimeMillis(); delta = currentTime - startTime;}
Whenever you want to start your DeltaTime timer, you just do time = System.currentTimeMillis;. This way, the variable "delta" is the amount of time between when you started the DeltaTime timer and when you end it using ClassNameHere.deltaTime();.
private static LocalTime timeDate(double d) {
//converts into a local time
return LocalTime.ofSecondOfDay((long)(d*3600%86400));
}
Input (d):
36.243356711275794
Output:
21:22:43
i started with total milliseconds, which I've converted to to total minutes and total seconds:
long minutes = TimeUnit.MILLISECONDS.toMinutes(itemDuration);
long seconds = TimeUnit.MILLISECONDS.toSeconds(itemDuration)
- TimeUnit.MINUTES.toSeconds(minutes);
Now I want to display the minutes and seconds in a mm:ss format (and if occasionally there are hours, then convert to hh:mm:ss format). how would i go about doing this?
thanks!
edit: I've tried using SimpleDateFormat, however it would display the wrong time in time zone that differ by half an hour vs a full hour. (ie: if the time zone was GMT +5:30 and the item duraction was 5 seconds, the app would display 30:05 instead of 00:05).. however it works fine for other time zones that differ by a full hour, such as GMT+5.
unless i'm doing something wrong with the SimpleDateFormat?
private static final SimpleDateFormat mLengthFormatter = new SimpleDateFormat("mm:ss", Locale.getDefault());
(also, just out of curiosity, if I use a SimpleDateFormat, and the number of minutes is greater than 2 digits, then what would happen? would it max out at 99?)
Could probably do it with a string formatter.
formatter.format("%2d:%2d", minutes,seconds);
I need to determine if a time stamp is an exact hour (i.e. it represents a time with no minutes, seconds or milliseconds components) - using primitives only. The code is called several hundred times per second and I don't want the overhead of a Calendar or other object.
I've tried this but rounding errors cause the comparison to fail.
float hours = (time / 3600000f);
boolean isExactHour = hours == (int)hours;
For example, if time = 1373763600470, hours = 381601.03125. That time stamp represents 01:00:00:000 GMT today and hours should be 381601.
Any ideas for a quick and simple way to do this? Thanks!
[EDIT]
It seems that this is more complex than at first sight (when is it not? :)
For clarity, I don't care about time zones, nor leap seconds. The time stamp is generated by a method which returns the previous midnight - i.e. 13 July 2013 00:00:00:000 for today. I am then calculating, for any time stamp in an array of longs which is always this initial time stamp plus/minus an exact multiple of 5 minutes. My aim to to determine if a given stamp is "top of the hour". I might have edge cases where the multiple of 5 minutes overlaps a year end but I can live with those.
(time % 36000000) == 0
Surely this is obvious?
EDIT
To get accuracy w.r.t. leap seconds, assuming a lookup table of leap seconds indexed by year since (say) 1970, something like:
((time-leapSeconds[(int)(time/(1000*60*60*24*365.2425))-1970]*1000) % 3600000) == 0
Programmers needing this level of accuracy should also see all of Einar's comments below.
There is a lot of similar topics but I couldn't find something similar then my problem. I've found only how to calculate if for example second time is greater then first time, like:
22:00
23:00
The result is easy to get. Just subtract second time with first using Date API. Difference is in milliseconds and you can easily convert them in seconds/minutes..
What I want to know, how to get difference between time in first day and time in second day, for example:
22:25
06:30
Difference should be 8 hours and 5 minutes.
Or another example
19:00
00:00
Difference should be 5 hours.
How to calculate time in this way? Any help is appreciated.
Convert your date and time to TimeStamp (It's just the long representation of a date in milliseconds since Jan. 1, 1970.), then calculate difference, and transferred from milliseconds to hours.
Also check this
Use Calendar class. Set your day, hour and minutes and finally subtract those dates (in milliseconds) and you will convert result in hour, minutes and seconds.
How can I calculate the time differences in 24 hour if the user input is 2255 and 2305 the output should be 10 minutes. I got an idea is to separate the input to 2 parts, 2 digits and 2 digits. the first 2 digits is the hour, times it to 60 to make it to minutes. Then plus it with the second 2 digits and then calculate the differences. I dont want use any Date Calendar data type or API to solve it. Thanks
String time1 = "2255";
String time2 = "2305";
SimpleDateFormat format = new SimpleDateFormat("HHmm");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
difference is in millis you can convert it to any unit or you can use DurationFormatUtils from apache-commons to pretty format it.
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
apache commons has really nice utility functions, apache-commons (lang)
How to get first 2 digit without using String chartAt.
Highest two digits: number / 100
Lowest two digist: number % 100
But what would you do if user enter 3:05 or 3-05? I think it's problem of usability. Best solution is making UI definitely understandable for user. For example you can use separate fields for hours and minutes.