Reputation:
I have two int variables containing
Int hour=13,minute=8;
I want to convert them into a time object in format like 13:08:00.0000000
What's the standard
way of doing it and of making time object out of this string?
Eventually I will convert back that time object into string for use but I want to standardize the string.
Upvotes: 0
Views: 234
Reputation: 7556
May not be the most smart way, but it should work. You can change your hour and minute to String, then use SimpleDateFormat to format it:
String originalString = new Integer(hour).toString()+":"+new Integer(minute).toString()+":00.000000";
Date date = new SimpleDateFormat("HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("HH:mm:ss").format(date);
See this
Upvotes: 0
Reputation: 39836
"standard" is a very abstract concept, specially in computing, and even more with Date time, and I've seen people doing all type of crazy things, I'll answer what I believe is the best way of dealing with it.
manipulation:
For general manipulation during Runtime handling of time you should use a Calendar
object, either using the static Calender.getInstance()
or directly instantiating a GregorianCalendar
with new
. There're several other classes that deal with the same problem like Time
or Date
but all of them are either limited or not recommended anymore.
With this class you can use to compare, transform, set values, etc.
on screen representation/format:
To format a representation of the Calendar
on screen (a String) you can use either a DateFormat
or a SimpleDateFormat
. They will make the human readable value you need to show on screen, by calling DateFormat.format(calendar.getTime());
save/restore:
Last but not least, if you want to save this value (in a SharedPreferences, SQL database, or anywhere) you should use a long
as UNIX EPOCH. Number of milliseconds since 1/1/1970. To get the current value on Runtime you can use System.currentTimeMillis()
or to set/extract from a Calendar
is as simple as Calendar.getTimeInMillis()
Calendar.setTimeInMillis(long milliseconds)
Upvotes: 0
Reputation: 20513
You could use Java's Calendar or Date object. I suggest using JodaTime, very powerful and easy to use.
With JodaTime
DateTime dt = new DateTime().withHourOfDay(hour).withMinuteOfHour(minute);
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss.SSS");
String dateString = fmt.print(dt);
Upvotes: 1