Fireburn
Fireburn

Reputation: 1021

Getting date/time in server side code for specific Timezone

On the server code I would like to get the "Day" but not of server date/time but of a specific timezone, GMT+8 specifically.

I have this code:

DateFormat formatter = new SimpleDateFormat("EEEE", Locale.ENGLISH);
String day = formatter.format(new Date()).toUpperCase();
availabilities.add(Availability.builder()
   .day(day)
   .from(LocalTime.now())
   .to(LocalTime.now())
   .build());

How do I get the "day" for the specific timezone and also have to build a LocalTime.now() which will return a LocalTime object but not the current time of the said timezone.

For instance as of this writing GMT+8 now is ~6:25 am so that would be the one that LocalTime.now() returns instead of the cloud server which is in the different timezone.

Upvotes: 0

Views: 52

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102812

SDF and new Date() are old API and you don't want these. For example, Date is a lie; it does not represent a date whatsoever, it actually represents an instant in time. This is dumb - that's why there is a new API.

EDIT: Made it simpler by invoking the now method of ZonedDateTime.

private static final ZoneId TARGET_ZONE = ZoneId.of("Singapore");


ZonedDateTime atTarget = ZonedDateTime.now(TARGET_ZONE);
DayOfWeek whatYouWant = atTarget.getDayOfWeek();

NB: You can go with +8 explicitly, then you're looking for an OffsetDateTime, and atOffset(ZoneOffset.ofHours(8)), but that's... weird. Who could possibly want 'UTC+8'? Nobody, except airplanes and military operations in a certain zone, and surely that's not your target audience.

Upvotes: 2

Related Questions