Friday, October 12, 2018

[Java] Date formatter

Reusable utility for formatting date.


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public static String formatDate(Date date, String format) {

     
   if(date == null || format == null) {
      throw new NullPointerException("Date or Format is null.");
   }

   return new SimpleDateFormat(format).format(date);


}



Sample call to the method:

Date date = Calendar.getInstance().getTime();
String format = "YYYY-MM-dd";
String formattedDate = formatDate(date,format);

No comments:

Post a Comment