I want to print the current date in this format - 01-JUN-20 08.55.27.577984000 AM UTC. Tried lot of formats in SimpleDateformat but none is working. What is the right way to print like this?
Asked
Active
Viewed 316 times
0
-
1I recommend you don’t use `SimpleDateFormat`. That class is notoriously troublesome and long outdated. Instead use `DateTimeFormatter` and other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 01 '20 at 10:00
-
1If you could use `DateTimeFormatter` that would be better, and the pattern you need will be `"dd-MMM-yy hh.mm.ss.n a z"` which is exactly what you need, nanoseconds and timezone included. – matteobarbieri Jun 01 '20 at 10:04
-
1Close, @matteobarbieri. If the fraction of second is, say 0.001234, one `n` will result in `.1234000`, so wrong. I suggest `ZonedDateTime.now(ZoneId.of("Etc/UTC")).format(DateTimeFormatter.ofPattern("dd-MMM-yy hh.mm.ss.SSSSSSSSS a z", Locale.ENGLISH)).toUpperCase(Locale.ENGLISH)` (just gave `01-JUN-20 10.40.44.076408000 AM UTC` on my computer). – Ole V.V. Jun 01 '20 at 10:41
1 Answers
0
SimpleDateFormat
You can use the following pattern:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimeFormatting {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy hh.mm.ss.SSS a Z");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String formatted = formatter.format(new Date(2015, 4, 4, 13, 7, 19)); //One example date
System.out.println(formatted);
}
}
This will give the output 04-05-15 11.07.19.000 AM +0000
where +0000
equals to UTC
.
Explanation of the pattern dd-MM-yy hh.mm.ss.SSS a Z
:
dd
= the dayMM
= the monthyy
= the yearhh
= the hourmm
= the minutess
= the secondSSS
= the millisecond. There does not exist a reference to nanoseconds inSimpleDateFormat
(see this answer).a
= to show AM/PMZ
= to show the timezone
Additional information
Please note: SimpleDateFormat
is deprecated. You should use DateTimeFormatter
. One big advantage is that you can also have the nanoseconds (n
).
One example:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.ZoneOffset;
public class TimeFormatting {
public static void main(String[] args) {
ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy hh.mm.ss.n a 'UTC'").withZone(ZoneOffset.UTC);
String timeDate = time.format(formatter);
System.out.println(timeDate);
}
}
Edit:
If you want to have UTC
instead of +0000
with SimpleDateFormat
you can use dd-MM-yy hh.mm.ss.SSS a zzz
instead.
-
But, this prints the timezone in number +0000,-4000 ..like that..I want it to be printed like UTC,America/Montreal , IST etc – Praveen Nvs Jun 01 '20 at 10:05
-