Java converts UTC timestamp to local DateTime

I know that there are dozens of UTC Time / Date To / From local time conversion response messages, but they did not help me figure out my problem. My question is: Having a UTC timestamp, how can I get a local DateTime? This is what I have now, but it just converts the timestamp to DateTime format.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getDefault()); sdf.format(new Date(timestamp * 1000)); 

Edited: I save the UTC timestamp in the cloud so that each device (Android / iOS) can request and convert the timezone to it.

+4
source share
3 answers

Try it with me.

 public String getDateCurrentTimeZone(long timestamp) { try{ Calendar calendar = Calendar.getInstance(); TimeZone tz = TimeZone.getDefault(); calendar.setTimeInMillis(timestamp * 1000); calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis())); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date currenTimeZone = (Date) calendar.getTime(); return sdf.format(currenTimeZone); }catch (Exception e) { } return ""; } 
+14
source

You can try this

  String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss az" ; final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String dateTimeString = sdf.format(new Date()); System.out.println(dateTimeString); // current UTC time long timeStamp=sdf.parse(dateTimeString).getTime(); //current UTC time in milisec Calendar cal = Calendar.getInstance(); cal.setTime(new Date(timeStamp)); cal.add(Calendar.HOUR_OF_DAY, 5); cal.add(Calendar.MINUTE, 30); System.out.println(sdf.format(cal.getTime())); // time relevant to UTC+5.30 
0
source

U can use Joda time to convert local to UTC and vice versa for example local to UTC

 DateTime dateTimeNew = new DateTime(date.getTime(), DateTimeZone.forID("Asia/Calcutta")); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss"); long milis = 0; try { milis = simpleDateFormat.parse(datetimeString).getTime(); } catch (ParseException e) { e.printStackTrace(); } 
0
source

Source: https://habr.com/ru/post/1501236/


All Articles