Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 456
Shepard Avatar asked Aug 04 '15 10:08

Shepard


People also ask

How do you change date format to MM DD YYYY in Java?

Java SimpleDateFormat ExampleString pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);

How do I change the format of a Date object in Java?

Create Simple Date Format // Date Format In Java String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); According to the example above, the String pattern will be used to format dates, and the output will be shown as "yyyy-MM-dd".

Which statement can be used to display date in desired format in Java?

Creating A Simple Date Format SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The specified parameter “pattern” is the pattern used for formatting and parsing dates.


1 Answers

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
like image 188
Ruchira Gayan Ranaweera Avatar answered Oct 12 '22 09:10

Ruchira Gayan Ranaweera