Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat in UTC to String in given format [duplicate]

I need add something to this line:

String date = new SimpleDateFormat("dd-MMM-yy hh.mm.ss").format(new Date()).toUpperCase();

because I need time from UTC, not from my current location. Could you please help me?

like image 846
Taki Jeden Avatar asked May 16 '26 04:05

Taki Jeden


1 Answers

You can either use this:

final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());

or have a look at java8 LocalDateTime and DateTimeFormat API. java.util.Date and especially SimpleDateFormat are kinda outdated and I would recommend against using SimpleDateFormat if possible as it is not thread save which may bite you when using streams or something.

Java 8 alternative:

String now = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("dd-MMM-yy HH.mm.ss"));
like image 85
Dennis Ich Avatar answered May 18 '26 17:05

Dennis Ich