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:

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

I need a conclusion:

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

Any ideas?

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

  Aug 14 10:58:55 Aug 4 10:58:55 
+5
source share
3 answers

If you are worried about white space, just add empty space to the formatter.

 "MMM d HH:mm:ss" 

For instance:

 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())); 

Output:

 Aug 4 15:50:25 
+2
source

AFAIK there is no template in SimpleDateFormat for this.

The easiest way is the easiest. Check the length of the string and add extra space if necessary. Since all other elements have a fixed length, there is no need for a more complex 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 to be fantastic (like RegExp), it's a little more reliable, but not worth the effort IMO

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

Check out this method of the SimpleDateFormat class:

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

and provide a custom implementation of FieldPosition .

+2
source

All Articles