简体   繁体   中英

Storing time elements in a structure in Java

I often need to manipulate time. The Calendar class is good for working with dates and times but I can't seem to find a simple way of just storing elements like hours, minutes and seconds into some structure. There seems to be a lot of conversion required from strings to actual ints. I can always create my own class and just store the elements into fields but it would be nicer if a class exists that provides more functionality (adding time, etc) yet keeps it simple for storing and accessing. I'm looking for something like this:

Time time = new Time();
time.parse("13:30:15");
t.Hour = 13;
t.Minute = 30;
t.Second = 15;

Are there any Java classes that exist that do something simple like this. Here's how I do it now. What a horrific amount of code just to parse out hours and minutes:

String time = "17:30";

TimeInfo timeInfo = new TimeInfo();
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(time);

Calendar calendar = Calendar.getInstance();
calendar.setTime(d);

timeInfo.Hours = calendar.get(Calendar.HOUR_OF_DAY);
timeInfo.Minutes = calendar.get(Calendar.MINUTE);
timeInfo.Seconds = calendar.get(Calendar.SECOND);

class TimeInfo
{
  public int Hours;
  public int Minutes;
  public int Seconds;
  public boolean Is24HourFormat;
}

JodaTime is one of external libraries that help manipulate times easily. You can add time. Also find the difference between times.

You also might want to check the difference between interval and duration which are concepts in jodatime lib. [ SO post ]

Refer its javadoc for more info

try this approach

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date d = cal.getTime();
SimpleDateFormat f =new SimpleDateFormat("hh:mm:ss aa");
System.out.println(f.format(d));

I think the java.util.Calendar gives you everything you need. Have a look at Calendar#set() .

public final void set(int year, int month, int date, int hourOfDay, int minute, int second)

Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND. Previous values of other fields are retained. If this is not desired, call clear() first.

I would prefer to use DateUtils from Commons Lang. This along with Calendar and DateFormat(SimpleDateFormat) should suffice all the date requirements in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM