How to format longs in android to always display two digits - java

I have a countdown timer which shows seconds from 60 to 0 (1 min countdown timer). When it reaches 1 digit numbers such as 9,8,7.. it shows 9 instead of 09. I tried using String.format("%[B]02d[/B]", x); where I converted x from long to string. It didn't work.
I want an equivalent of String.format("%2d", 1)

You can accomplish it with DecimalFormat:
NumberFormat f = new DecimalFormat("00");
long time = 9;
textView.setText(f.format(time));
Output:
09
Or you can use String.format() as well:
String format = "%1$02d"; // two digits
textView.setText(String.format(format, time));

Use: text.setText(String.format("%02d", i)); where i is the integer value

Why not just use an if statement?
String str = x < 10 ? "0" + String.valueOf(x) : String.valueOf(x);
That should do the trick.

TextView time;
int hour=0,minute=0,second=0;
time.setText((String.format("%02d", hour))+":"+(String.format("%02d", minute))+":"+(String.format("%02d", second)));
time to TextView

Try using this:
tv.setText(new DecimalFormat("##").format(var));

Related

Using a Ternary Operator to a "0" within the statement

I'm trying to format a time using a variable input. If a user enter an hour as 1 - 9 the out put would include a "0", and the same for minutes. So far if a user enters 1 hour 3 minutes the output reads 1:3 instead of 01:03.
How do I get the extra 0 in front of numbers less than 10.
Here's the code.....
import java.util.Scanner;
public class FormatTime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int MinutesInput;
int HoursInput;
int Hours;
int Minutes;
{
System.out.println("Enter hours between 1 and 24");
Hours = input.nextInt();
System.out.println("Enter minutes between 1 and 59");
Minutes = input.nextInt();
{
**//THIS NEXT LINE IS THE PROBLEM**
HoursInput = Hours < 10 ? "0" + Hours : Hours;
System.out.print(HoursInput + ":");
}
{
**//THIS NEXT LINE IS THE PROBLEM**
MinutesInput = (Minutes < 10) ? "0" + Minutes : (Minutes);
System.out.print(MinutesInput);
}
System.out.println();
}
}
}
How do I get the extra 0 in front of numbers less than 10.
You don't, while the target variable is of type int. An int is just a number, not a string - whereas "0" + Hours is a string.
int values don't contain any sort of string representation - the number sixteen is just as much "0x10" or "0b10000" as it is "16"... or even "00016" if your decimal representation allows much digits. ("00016" may be mis-interpreted as fourteen, however, if it's parsed as an octal string...)
Use DecimalFormat to convert numbers into strings in your desired format, or String.format, or possibly just PrintStream.printf if you want to write it straight to the console.
I'd also strongly recommend that you use camelCase for your local variables, and only declare them when you first need them.
Perhaps you should be using
System.out.printf("%02d:%02d%n", Hours, Minutes);
You are confusing int and String types:
int HoursInput;
//...
HoursInput = Hours < 10 ? "0" + Hours : Hours;
There are two problems with your code: you are trying to store string "07" (or similar) in an int. Secondly even if it was possible, 07 is equivalent to 7 as far as integer types are concerned (well, leading 0 has a special octal meaning, but that's not the point).
Try this instead:
String hoursInput;
//...
hoursInput = Hours < 10 ? "0" + Hours : "" + Hours;
you must use String variables or use format method (similar to sprintf from c) from String class.
String time = String.format("%02d:%02d", hours, minutes );

Get timestamp and convert it to string

I'm using this to get current timestamp in seconds and add it to a string Double.toString((System.currentTimeMillis()/1000))
However instead of decimal notation I get "1.23213E9". How do I switch to the decimal notation ?
The shortest is
String secs = "" + System.currentTimeMillis() / 1000;
If you want to retain milli-seconds you can use
String secs = String.format("%.3f", System.currentTimeMillis() / 1000.0);
produces a String like
1342604140.503
Try this:
TimeUnit.MILLISECONDS.toSeconds(((System.currentTimeMillis());
String.valueOf(System.currentTimeMillis() / 1000)
that should do the trick? No need to convert it to a double
If you need to deal with a Double you could do something like this:
double myNum = 1.23213E9;
String myString = NumberFormat.getInstance().format(myNum);
System.out.print(myString);

How to use a Time format in Android

I am trying to take have a time that counts down all the way to 0 from 1 minute.
I have already created my timer. I just need to know how do i convert a int such as 100 to a String to show 1:00 as in a minute and keep counting down like minus 1 secodn from the int and convert it to the String :59?
Any suggestions?
If I understand your question correctly you simply want to divide your number by 60 to get the minutes and then mod your number by 60 to get the seconds and then concat the strings.
int remainingTime = 100;// or whatever number of seconds you have left
String min = (remainingTime / 60) + "";
String sec = (remainingTime % 60) + "";
String remainingTimeStamp = "min" + ":" + "sec";
If you want to get fancy with it, check to see if min and sec are less than 10 and append a leading zero, so that it looks like 01:05 rather than 1:5
I'm not sure what you mean by "I already have my timer". I'll wait for you to update your question, rather than speculate as to what you might mean, before I continue elaborating.
To add to this, check the http://developer.android.com/reference/android/text/format/DateUtils.html class. Note that this is not in 'org.apache' which has another DateUtils class.
Edit:
Since it appears you were looking for formatting 100 seconds here is it formatted:
SimpleDateFormat df = new SimpleDateFormat("mm:ss");
String formatted = df.format(remainingTime * 1000);

About GregorianCalendar : the same input but different output in java

I want to use milliseconds to set a new date in my program,but it doesnt work. Is there anybody can tell me why it doesnt work?
Calendar r_1 = new GregorianCalendar(2011,0,1);
r_1.add(Calendar.DAY_OF_MONTH,2);
System.out.println(r_1.getTime());
long date_1 = r_1.getTimeInMillis() + 2*24*60*60*1000;
r_1.setTimeInMillis(startTime1);
System.out.println(r_1.getTime());
It works both very correct , but if i change the day from 2 to 25,then it doenst work .
----------the output is correct ,it is 2011/01/26 ----------
Calendar r_1 = new GregorianCalendar(2011,0,1);
r_1.add(Calendar.DAY_OF_MONTH,25);
System.out.println(r_1.getTime());
-----------the output is incorrect now ,it is 2010/12/07------
long date_1 = r_1.getTimeInMillis() + 25*24*60*60*1000;//i have change 2 to 25
r_1.setTimeInMillis(startTime1);
System.out.println(r_1.getTime());
Thanks
The expression 25*24*60*60*1000 is an integer, and you have overflowed the size of an integer, creating a negative number.
Your expression is 2,160,000,000 milliseconds. The largest value an int can hold is 2,147,483,647.
To fix this, you have to force the expression to be a long, as follows
25L*24*60*60*1000
25*24*60*60*1000 is too large to fit in an int.
Try 25L*24*60*60*1000 which is a long constant.
Try something like that:
final long k = 25*24*60*60*1000L;
long date_1 = r_1.getTimeInMillis() + k;

Which API can I use to format an int to 2 digits?

What API can I use to format an int to be 2 digits long?
For example, in this loop
for (int i = 0; i < 100; i++) {
System.out.println("i is " + i);
}
What can I use to make sure i is printed out like 01, 02, 10, 55 etc (assuming a range of 01-99 )
You could simply do
System.out.printf("i is %02d%n", i);
Have a look at the documentation for Formatter for details. Relevant parts are:
The format specifiers for general, character, and numeric types have the following syntax:
%[argument_index$][flags][width][.precision]conversion
(In this particular case, you have 0 as flag, 2 as width, and d as conversion.)
Conversion
'd' integral The result is formatted as a decimal integer
Flags
'0' The result will be zero-padded
This formatting syntax can be used in a few other places as well, for instance like this:
String str = String.format("i is %02d", i);
String class actually do formatting.
For your case, try:
String.format("%02d",i)
You can use the DecimalFormat object.
DecimalFormat formatter = new DecimalFormat("#00.###");
int test = 1;
System.out.println(formatter.format(test));
Will print "01".

Categories

Resources