Time - Specify X seconds / minutes, and basic arithmetic - java

I am wondering how one would go about specifing a certain amount time, say X seconds. I'm writing the behaviour for a class that represents a Till (as in, a supermarket till), and whish to specify how long it takes to check out 1 item.
I'm doing this so once I receive the number of items a customer has, the time taken to serve the customer is simply:
ITEM_CHECKOUT_TIME * NumberOfItems;
ITEM_CHECKOUT_TIME would be a constant, and what I wish to specify. Some basic arithmetic would be done on this constant, like above.
Sure, I could use a double to represent the time, but I was wondering if it's actually possible with the Time classes, or anything else specifically for this task.
Thanks!

I would not use a double to represent time. I would probably represent it as a whole number of milliseconds (or nanoseconds). If you're looking for something fancier, you might want to look at the Duration class in the Joda-Time library:
http://joda-time.sourceforge.net/key_duration.html

Related

How to indicate some fields are not supported

Trying to move from Calendar to the new Java 8 time on Android. Is there a way to indicate that a time or date field is not supported? I can use the 'Truncate' method that will set all time fields of a shorter duration to zero, so a time stamp like 2020-09-30T10:37:15.345-04:00 can be truncated say at the minutes level. But that will leave 2020-09-30T10:00:00.00-04:00.
However, what I want to indicate is that the clock does not have minutes or less precision so that when one tries to read the minutes or seconds, there will be some indication that there are no such fields or that they are unknown. Zero is a valid value.
Right now in the Calendar case I have to add numerous methods to a class to indicate that. For example, I made a class called TimeStruct which wraps a Calendar. If I take a time stamp like 2020-10-01T04:55 it does not have minutes. So to keep that information I have a variable 'isSecondsSet' and set it to false. I create the Calendar from the elements I DO have. But as soon as I call something like Calendar.getTimeInMillis() the seconds and milliseconds fields get set to 0 and are indicated as set. So my additional variables let me know that there was no seconds field.
I was hoping that the new classes would no longer require me to keep my own indicators and I would also be able to parse something like 2020-10-01T04:55. I could not, but I could parse a full time stamp. So if I do that and truncate, can I indicate that the truncated fields are not supported? That way I wont use a value of 0 in the seconds.

Run code every X seconds (Java)

This is not super necessary, I am just curious to see what others think. I know it is useless, it's just for fun.
Now I know how to do this, it's fairly simple. I am just trying to figure out a way to do this differently that doesn't require new variables to be created crowding up my class.
Here's how I would do it:
float timePassed = 0f;
public void update(){
timePassed += deltatime;//Deltatime is just a variable that represents the time passed from one update to another in seconds (it is a float)
if(timePassed >= 5){
//code to be ran every 5 seconds
timePassed -= 5f;
}
}
What I want to know is if there is a way to do this without the time passed variable. I have a statetime (time since loop started) variable that I use for other things that could be used for this.
If the goal really is to run code every X seconds, my first choice would be to use a util.Timer. Another option is to use a ScheduledExecutorService which adds a couple enhancements over the util.Timer (better Exception handling, for one).
I tend to avoid the Swing.Timer, as I prefer to leave the EDT (event dispatch thread) uncluttered.
Many people write a "game loop" which is closer to what you have started. A search on "game loop" will probably get you several variants, depending on whether you wish to keep a steady rate or not.
Sometimes, in situations where one doesn't want to continually test and reset, one can combine the two functions via the use of an "AND" operation. For example, if you AND 63 to an integer, you have the range 0-63 to iterate through. This works well on ranges that are a power of 2.
Depending on the structure of your calling code, you might pass in the "statetime" variable as a parameter and test if it is larger than your desired X. If you did this, I assume that a step in the called code will reset "statetime" to zero.
Another idea is to pass in a "startTime" to the update method. Then, your timer will test the difference between currentTimeMillis and startTime to see if X seconds has elapsed or not. Again, the code you call should probably set a new "startTime" as part of the process. The nice thing about this method is that there is no need to increment elapsed time.
As long as I am churning out ideas: could also create a future "targetTime" variable and test if currentTimeMillis() - targetTime > 0.
startTime or targetTime can be immutable, which often provides a slight plus, depending on how they are used.

Protocol Buffer: How to define Date type?

I'm trynig to write a proto file that has a Date field which is not defined as a type into Protocol buffer.
I have read the following post but I couldn't figure out a proper solution that suits me :
What the best ways to use decimals and datetimes with protocol buffers?.
I'm trying to convert the proto file to a java .
My answer in the linked post relates mainly to protobuf-net; however, since you are coming at this from java I would recommend: keep it simple.
For dates, I would suggest just using the time (perhaps milliseconds) into an epoch (1 Jan 1970 is traditional). For times, just the size in that same unit (milliseconds etc). For decimal, maybe use fixed point simply by scaling - so maybe treat 1.05 as the long 1050 and assert always exactly 3dp (hence fixed point).
This is simple and pragmatic, and covers most common scenarios without making things complicated.
I'm not sold on this idea, but I'm really not sold on the idea of storing dates (which aren't instants in time) as a timestamp, so here's my suggestion.
Convert your date into a human-readable integer (e.g. 2014-11-3 becomes 20141103) and store this integer value. It contains exactly the data you need, is simple to create and parse, and takes up minimal space. Additionally, it is ordered and has a one-to-one mapping of dates to valid values (granted, invalid numbers are possible, such as 20149999, but these are easy to detect). In contrast, there are approximately 86400 valid timestamps that represent each day.
NB: There is a discussion on DBA SE criticizing this method of date storage, but in that context a specialized date type exists, which obviously isn't the case here.

Better way to check if a joda.time.Interval spans exactly 1 calendar week (accounting for daylight savings etc)

Is there a better way of doing this?
boolean oneCalendarWeek = interval.getStart().plusWeeks(1).equals( interval.getEnd() );
I guess the following won't work because of the way equals is implemented...
boolean oneCalendarWeek = interval.toPeriod().equals( Weeks.ONE );
From the comments:
i really want to know if the api supports something like my second example which i think is clearer than the first
While the example using Weeks.ONE does not work (since Period.equals() first checks if the two Period instances support the same number of fields, and Weeks.ONE only supports one field), this should work instead:
boolean oneCalendarWeek = interval.toPeriod().equals( Period.weeks(1) );
Here is a code sample that tests this for an interval that starts before the start of DST and ends while in DST. However, I'm not 100% sure how this would behave if the start or end time of the Interval fell exactly on the DST boundary.

Schedule notation (time ranges)

I have some code which needs to do things based on a schedule: e.g. during business hours do X, after hours do Y. The schedule will be defined by our customer's so I need a notation which can be written by people and parsed by my program. I'm thinking of something like:
12/25:0730-1730 Do Y
[Mo-Fr]:0730-1730 Do X
[Mo-Tu]:1730-0730 Do Y
Fr:1730-Mo:0730 Do Y
There will definitely be weekly variation. Yearly variation (holidays) seems likely. I would like a notation that is efficient and flexible.
I also need java code which will parse the time ranges and tell me which range a given date time is in.
I've searched the web and found nothing. Closest is CRON notation, which is not quite what I need.
Any one know of an existing notation definition and implementation?
Thanks,
For Java Joda time (Scala wrapper scala-time) is a powerful library for time calculations. You could look at the google-rfc-2445 which does something like what you are asking for (?).
If you are looking for a Java scheduler http://www.quartz-scheduler.org/ is a good option.
I don't think you will find something out of the box. In such cases it's better to do the implementation by yourself and have a full control of the code. You can use antlr to create a parser.
Add a notion of priority to your syntax. Then it will be easier to schedule someting
01.01.2011-31.01.2011 prio 1 do-idle-stuff
[Mo-Fr] prio 2 do-work
[Sa-Su] prio 2 weekend
10.02.2011-17.02.2011 prio 3 go-on-holidays

Categories

Resources