Shepard
Shepard

Reputation: 1111

Space instead of leading 0 Date Java

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss"); 
    System.out.println(sdf.format(new Date()));
    SimpleDateFormat sdff = new SimpleDateFormat("MMM d HH:mm:ss"); 
    System.out.println(sdff.format(new Date()));

Output is:

    Aug 04 10:58:55
    Aug 4 10:58:55

I want output to be:

    Aug 04 10:58:55
    Aug  4 10:58:55

Any ideas?

But if day has two numbers I need it to have one space:

    Aug 14 10:58:55
    Aug  4 10:58:55

Upvotes: 6

Views: 765

Answers (3)

SJuan76
SJuan76

Reputation: 24895

AFAIK no pattern in SimpleDateFormat to do that.

The easiest way is the simplest. Check the string length and add an extra space if needed. Since all the other items have fixed length, there is no need for a more complicated check.

SimpleDateFormat sdff = new SimpleDateFormat("MMM d HH:mm:ss");
if (sdff.length == 14) {
   sdff = sdff.substring(0,4) + " " + sdff.substring(4);
}

If you want it fancy (aka RegExp), it is kind of a little more robust but not worth the effort IMO

SimpleDateFormat sdff = new SimpleDateFormat("MMM d HH:mm:ss");
sdff = sdff.replaceAll(" (\\d) ", "  $1 ");

Upvotes: 2

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

If you are bother about white space just add a white space to formatter.

"MMM  d HH:mm:ss"

Eg:

Calendar calendar=Calendar.getInstance();
int day=calendar.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat sdf;
if(day>9){
  sdf = new SimpleDateFormat("MMM dd HH:mm:ss");
}else{
  sdf = new SimpleDateFormat("MMM  d HH:mm:ss");
}
System.out.println(sdf.format(new Date()));

Out put:

Aug  4 15:50:25

Upvotes: 2

ka4eli
ka4eli

Reputation: 5424

Check out this method of SimpleDateFormat class:

public StringBuffer format(Date date, StringBuffer toAppendTo,
                               FieldPosition pos) { ...}

and provide custom FieldPosition implementation.

Upvotes: 2

Related Questions