Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

sorting - How do you compare Day of week and Time in Java

How do you compare "Friday 2:00 PM" against "Thursday 4:00 PM" in Java?

Input array: Friday 2:00 PM Thursday 2:00 AM Saturday 4:00 PM

Output: Thursday 2:00 AM Friday 2:00 PM Saturday 4:00 PM

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My solution would be to build a little class to represent the times. We could call it TimeOfWeek or WeeklyRecurringEvent or whatever fits your domain, please try to choose wisely. The class would have two instance fields, a DayOfWeek for the weekday and a LocalTime for the time. DayOfWeek and LocalTime are in java.time (introduced in Java 8 and backported to Java 6 and 7). My class would have a constructor accepting a String argument like "Friday 2:00 PM" and would parse it into the two instance fields. I believe the same DateTimeFormatter could be used for both, so this could be a class constant (private static final field). DayOfWeek does not have a parse method, so you would need something like DayOfWeek.from(yourDateTimeFormatter.parse(yourString)).

Your class should implement Comparable so you can sort your objects by their natural order. In your compareTo method compare day of week first, then time if day is the same. DayOfWeekare sorted naturally from Monday to Sunday; if your week begins on another day than Monday, you will need to handle it specially.

Your class could also have a ZoneId field for time zone, but assuming all your times are in the same time zone, there’s probably no reason.

Happy coding.

You may also see if you can find a class that fits your requirements somewhere out there; use your search engine. I don’t know of one, but you can never tell.

The classes in java.time are very often good for funny requirements about day and time. You can obviously have a date without a time or a time without a date. You can have a day of the year without a year (good for remembering your anniversary) and as mentioned a day of week without a week, and more. Unfortunately there isn’t a class to match your requirement of day of week and time exactly, which is why I suggest putting it together from two of the existing classes.

Edit: It seems from your Stack Overflow profile that you may be an Android programmer? If you want to use the java.time classes on Android, get and use the ThreeTenABP (the classes were first described in JSR-310, so that’s ThreeTen for JSR-310 and ABP for Android Backport).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...