Reputation: 73
I am making a math program that guesses the birthday of the user.
The user enters a number lets say : 75622 and i subtract a number from it to get the birthday, in this case 42682 -- 04/26/82
i want to be able to turn that integer into a string and then add the forward slash between the month, day and year.. and also add a 0 if it is only 5 digits and not 6 ( because of the month being 1-9).
I know how to use Integer.toString(int) to turn it into a string, but i do not know how to insert the forward slashes and the zero.
thank you kindly!
Upvotes: 1
Views: 66
Reputation: 201439
If you just want to convert the int
to a String
(with a leading 0
) you can use String.format
like
int num = 42682;
String s = String.format("%06d", num);
You might then use another String.format
and String.substring
to build your desired output, like
String output = String.format("%s/%s/%s", s.substring(0, 2),
s.substring(2, 4), s.substring(4));
System.out.println(output);
Which outputs (as requested)
04/26/82
Upvotes: 3
Reputation: 781
Please find answer below:
public class CreateDateFromNumber {
public static void main(String[] args) {
int number = 42682;
System.out.println(getDate(number));
}
public static String getDate(int number) {
String numberStr = Integer.toString(number);
String outputStr = "";
if (numberStr.length() != 5 && numberStr.length() != 6) {
throw new IllegalArgumentException(
"Number should be length of 5 or 6");
}
if (numberStr.length() == 5) {
numberStr = "0" + numberStr;
}
int var0 = 0;
while (var0 < numberStr.length()) {
String var1 = numberStr.substring(var0, var0 + 2);
outputStr = outputStr + var1;
if (var0 + 2 < numberStr.length()) {
outputStr = outputStr + "/";
}
var0 = var0 + 2;
}
return outputStr;
}
}
Upvotes: 1