I want to display time as "02 Sep 2020 at 12:24 AM"
(mind the at between date and time).
The current format I am using is "dd MMM yyyy hh:mm aaa"
,
which displays time as "28 Aug 2020 11:32 AM"
.
How can I put an at before the time?
You can add string literals to a date format by surrounding them with single quotes ('
):
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy 'at' hh:mm aaa");
// Here -------------------------------------------------^--^
String formatted = sdf.format(myDateVariable);
If you use java.time
for this, you can define a java.time.format.DateTimeFormatter
to parse a String
, use it to parse the String
to a java.time.LocalDateTime
and define & use another DateTimeFormatter
that includes the at
escaping it in the pattern by enclosing it in single-quotes:
public static void main(String[] args) {
String dateTime = "02 Sep 2020 12:24 AM";
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("dd MMM uuuu hh:mm a",
Locale.ENGLISH);
DateTimeFormatter outputDtf = DateTimeFormatter.ofPattern("dd MMM uuuu 'at' hh:mm a",
Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(dateTime, parserDtf);
System.out.println(ldt.format(outputDtf));
}
This code produces the output
02 Sep 2020 at 12:24 AM
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy 'at' HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));