-1

I have a simple class Message and some fields. One of them is the String date. I want to set formatted

public class Message {
  Long id;
  String text;
  String date;
} 

My goal is to set a formatted String of current date (Pattern is "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") while creating object Message. I can make new object by new or by @Bulder Lombok but how can i set string date ?

  • https://stackoverflow.com/questions/23068676/how-to-get-current-timestamp-in-string-format-in-java-yyyy-mm-dd-hh-mm-ss – Ratish Bansal Sep 18 '20 at 08:42
  • 1
    Does this answer your question? [How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"](https://stackoverflow.com/questions/23068676/how-to-get-current-timestamp-in-string-format-in-java-yyyy-mm-dd-hh-mm-ss) – Ashish Kamble Sep 18 '20 at 08:44
  • Please explain in more detail what your problem is. Usually the fields are made private and you have a constructor to set the fields during creation or setters for each field. – vanje Sep 18 '20 at 08:44
  • Problem is to set while creating object – Семен Немытов Sep 18 '20 at 08:46
  • Provide a parameterized constructor, maybe? – deHaar Sep 18 '20 at 08:52

2 Answers2

1

Considering the pattern you provided, an OffsetDateTime would be my choice:

public static void main(String[] args) {
    OffsetDateTime nowWithOffset = OffsetDateTime.now();
    System.out.println(nowWithOffset);
}

This output (some seconds ago)

2020-09-18T10:55:02.832+02:00

As you can see, your desired pattern matches the default one used by an OffsetDateTime.

I would make the attribute date an OffsetDateTime instead of a String and provide a simple method for a String representation, maybe like this:

public String getDateAsString() {
    return date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX");
}

and if you receive such a String and want to set your attribute, use a parameterized constructor or a setter / setting method, e.g.

public void setDateFromString(String date) {
    this.date = OffsetDateTime.parse(
                        date,
                        DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX"));
}

and better replace the y in the pattern by a u, because a y could cause trouble in some situations where an era would be required.

deHaar
  • 17,687
  • 10
  • 38
  • 51
-1
class Message {
Long id;
String text;
String date;

public Message() {
    this.date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));
    System.out.println(date);
}

}

answer
  • 1
  • Although this code might solve the problem, a good answer should also explain **what** the code does and **how** it helps. – BDL Sep 18 '20 at 09:25