0

I am making a program that puts a zero before a day or month if its < 10. I work with the ternary operator and it works well if my dates are < 10.

11-02-1999 is good

But if its higher than zero it gives

11- 12-1999

I dont want that whitespace. How do i remove it. This is my code

nuldag = (dag < 10 ? '0' : '\0');
nulmonth = (month < 10 ? '0' : '\0');
System.out.println("Date is:  " +nulday+day+"-"+nulmonth+month+"-"+year);   
3
  • You have nuldag and dag, but you mean nulday and day. Commented Oct 6, 2015 at 21:16
  • I'm Dutch, just a wrong translation. Commented Oct 6, 2015 at 21:22
  • You used nulday later though, so you need to rename them to be the same. Commented Oct 6, 2015 at 21:22

1 Answer 1

5

You can't do this with a char. Use a String instead:

 String nuldag = (dag < 10 ? "0" : "");
 String nulmonth = (month < 10 ? "0" : "");
 System.out.println("Date is:  " + nuldag + day  + "-" + nulmonth + month + "-" + year);

EDIT:
I add the suggestion of Peter Lawrey that such formatting tasks are better solved using String formatting, e.g.

System.out.printf("Date is %2d-%2d-%d%n", day, month, year);
Sign up to request clarification or add additional context in comments.

1 Comment

This is the answer to the question but I would add that a better solution would be to use a format System.out.printf("Date is %2d-%2d-%d%n", day, month, year); +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.