In this example we will show three different methods to format date and time in Java.
Source Code
1) Using java.text.SimpleDateFormat
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample1 {
public static void main(String[] args) {
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date time = new Date();
System.out.println(df1.format(time));
System.out.println(df2.format(time));
}
}
Output:
2019-01-27 11:06:13
2019-01-27
2) Using String.format()
package com.beginner.examples;
import java.util.Date;
public class DateFormatExample2 {
public static void main(String[] args) {
String format1 = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS";
String format2 = "%1$tY-%1$tm-%1$td";
Date time = new Date();
System.out.println(String.format(format1, time));
System.out.println(String.format(format2, time));
}
}
Output:
2019-01-27 11:06:13
2019-01-27
3) Using java.util.Calendar
package com.beginner.examples;
import java.util.Calendar;
import java.util.Date;
public class DateFormatExample3 {
public static void main(String[] args) {
Date time = new Date();
Calendar c = Calendar.getInstance();
c.setTime(time);
int yyyy = c.get(Calendar.YEAR);
int MM = c.get(Calendar.MONTH) + 1;
int dd = c.get(Calendar.DAY_OF_MONTH);
int HH = c.get(Calendar.HOUR_OF_DAY);
int mm = c.get(Calendar.MINUTE);
int ss = c.get(Calendar.SECOND);
String time1 = String.valueOf(yyyy) + "-" + autoFill(MM) + "-" + autoFill(dd) ;
String time2 = time1 + " " + autoFill(HH) + ":" + autoFill(mm) + ":" + autoFill(ss);
System.out.println(time2);
System.out.println(time1);
}
private static String autoFill(int num) {
String result = "";
result = String.format("%02d",num);
return result;
}
}
Output:
2019-01-27 11:06:13
2019-01-27
Tips
Similarly, you can convert date time to formats like “dd-MMM-yyyy”,”dd/MM/yyyy”,”yyyy.MM.dd.HH.mm.ss”,etc.
References
Imported packages in Java documentation: