Function to format the local time

This is a statement that I use a lot in my code base:

 (LocalDateTime.now()).format(DateTimeFormatter.ofPattern("ssmmHHddMMMuu"))

Should I create a static method for this or is it overkill?

public static String getTodaysDateInFormat(String format){
  return (LocalDateTime.now()).format(DateTimeFormatter.ofPattern(format));
}

Answer

In general I think it’s OK to do so, because readability is improved, and DRY principle is encouraged.

But I’d make it a bit more generic not relying on LocalDateTime.now() and pass this as a parameter:

public static String getDateInFormat(DateTime d, String format) {
    return d.format(DateTimeFormatter.ofPattern(format));
}

The call

String formattedDate = getDateInFormat(LocalDateTime.now(),"ssmmHHddMMMuu");

is still shorter, and better readable.


Last but not least try to give that function a name, that expresses more precisely what it does. Something like formatDateToString() maybe.

Attribution
Source : Link , Question Author : RajKon , Answer Author : πάντα ῥεῖ

Leave a Comment