SRL Archive - Java Help and Tutorials

Formatting times


JPHamlett

2013-01-25 16:16:54

Does anyone know of an easier method to format times than a bunch of if else statements?


What I mean by format for example

[ATTACH]18822[/ATTACH]


That was just a quick job I could care less

Basically I need to get it output a hour variable and a minute variable like such hh:mm

here is my attempt, doesn't work, I have not debugged it thoroughly yet


@Override
public String toString(){
boolean pm = getHour() > 12;
String min ="" , hour = "";
if (getMinute() < 10){
min = "0" + getMinute();
} else {
min = "" + getMinute();
}

if (getHour() < 10){
hour = "0" + getHour();
}
if (getHour() > 12 && getHour() - 12 < 10){
hour = "0" + (getHour() - 12);
}
if (getHour() > 9 && getHour() < 13){
hour = "" + getHour();
}
if (pm){
return hour + ":" + min + " PM";
}
return hour + ":" + min + " AM";


}

getHour and getMinute just return a variable assigned to the class

Brandon

2013-01-25 16:22:42

From: JPHamlett
Does anyone know of an easier method to format times than a bunch of if else statements?


What I mean by format for example

[ATTACH]18822[/ATTACH]


That was just a quick job I could care less

Basically I need to get it output a hour variable and a minute variable like such hh:mm

here is my attempt, doesn't work, I have not debugged it thoroughly yet


@Override
public String toString(){
boolean pm = getHour() > 12;
String min ="" , hour = "";
if (getMinute() < 10){
min = "0" + getMinute();
} else {
min = "" + getMinute();
}

if (getHour() < 10){
hour = "0" + getHour();
}
if (getHour() > 12 && getHour() - 12 < 10){
hour = "0" + (getHour() - 12);
}
if (getHour() > 9 && getHour() < 13){
hour = "" + getHour();
}
if (pm){
return hour + ":" + min + " PM";
}
return hour + ":" + min + " AM";


}

getHour and getMinute just return a variable assigned to the class



Use the SimpleDateFormat in conjunction with the Date/Calendar class.


DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String TheData = df.format(DateInstance);


Specify the format of the date/time you want.. Do a quick search on the formats. In C# its dd/MM/yyyy/hh:mm:ss for day/month/year/hours/minutes/seconds..
MMM for January instead of Jan.
ddd for Monday instead of Mon.
yy for 09 instead of 2009.

etc..

JPHamlett

2013-01-25 17:03:02

All I want is the hour and minute…..I don't care about the rest, simply due to the assignment note caring. Is there a way to only get the hours and seconds or should I parse the string?

Brandon

2013-01-25 18:03:06

At the time of me posting this reply, the code below will print 06:05:43 PM

As I suggested earlier, formatting without if-else can be done using DateFormat and passing a date to the format function of that class as shown below:


public static void main(String[] args) {
Calendar C = Calendar.getInstance();
DateFormat DF = new SimpleDateFormat("hh:mm:ss a");
System.out.println(DF.format(C.getTime()));
}