0

UTC timezone - timezone user

I store my database value in UTC as a timestamp and retrieve it in my app.

But I need to know the difference to subtract/add the user's time zone.

So... I managed to do this by creating 2 timestamp, (current timestamp in UTC - current timestamp) and adding/subtracting the value stored in the database.

But I would like to know if there is any simpler way to do this, I thought about saving the date as a string ...

Does anyone have any tips or a better way to do such a thing?

HaMan
  • 13
  • 2
  • I downvoted for two reasons. (1) You have not shown us how you retrieve the date nor told us in what form you’ve got it. `java.sql.Timestamp`, for example?? (2) Your question seems poorly researched. You’re supposed to search before asking, and since there are *many* questions like this one already, I wonder how it can be that you don’t seem to have found any? – Ole V.V. Feb 01 '21 at 20:12
  • The answers suggest using `Date`, `SimpleDateFormat` and `TimeZone`. Think twice, no, at least three times before doing any of that. Those classes are poorly designed and long outdated. Instead consider `ZoneId` and other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 01 '21 at 20:14

2 Answers2

0

You have to store UTC time on your cloud server and after fetch data from API you need to do some calculation to convert your UTC time into the current user time zone like below one.

String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
M.Muzammil
  • 643
  • 9
  • 18
  • 2
    I totally forgot about TimeZone. I simply put TimeZone.getDefault (); and got the gmt value through getRawOffset timestamp -+ getRawOffset It looks like it worked correctly. – HaMan Feb 01 '21 at 17:34
  • If you found my answer helpful please mark upvote and accepted answer Thanks. – M.Muzammil Feb 01 '21 at 17:40
0
  • You should store only UTC time.

  • And based on your user timezone(You provide options to your users to set timezone). Then based on the app user's setting, you show him/her the time into his/her timezone.

  1. Import java.util.TimeZone
  2. Then retrieve UTC-time, which was saved on DB.
  3. Convert it java Date object (java.util.Date)
  4. Then set the user's timezone.
  5. Then convert UTC Datetime to user's Timezone
Date date = new Date(/*Your stored UTC datetime */)
DateFormat df = new SimpleDateFormat("dd-MM-yy HH:mm:SS z");
df.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
String sDate = df.format(date);
Md Kawser Habib
  • 1,966
  • 2
  • 10
  • 25