HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaModerate

Function to format the local time

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
localformatthefunctiontime

Problem

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

Solution

First of all, the parenthesis around LocalDateTime.now() are useless.

Now, let's see what we're really doing here:

return LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));


We're creating a unique LocalDateTime each time, but I am assuming that you always use the same format, and therefore the DateTimeFormatter.ofPattern(format) object will always be the same.

I would recommend not creating a method for this and instead extract a constant for the format:

private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("ssmmHHddMMMuu");


And then each time you need it, you just do

LocalDateTime.now().format(FORMAT);


A method named getTodaysDateInFormat provides exactly the same information as the above piece of code, therefore the method does not really provide any additional value.

I don't consider LocalDateTime.now().format(FORMAT) as duplicated code. Or rather: I'm considering just as much code duplication as a call to getTodaysDateInFormat().

Code Snippets

return LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("ssmmHHddMMMuu");
LocalDateTime.now().format(FORMAT);

Context

StackExchange Code Review Q#113945, answer score: 19

Revisions (0)

No revisions yet.