Вопрос

I am having trouble finding how how to convert a unix timestamp to normal date time for my Android app. In my use case all the reports of the events are submitted in US Mountain time. The server handles the time and stores the correct unixtime. However when my app then retrieves the report time from the server it needs to display the unix timestamp in US Mountain timezone no matter where in the world the user is located. Also it needs to handle the change in the GMT offset caused by daylight savings.

Below is what I have tried but I keep getting errors. It says that it can not resolve the setTimeZone method and that it expects a "," within that function.

//TODO: convert to readable time
String EventRegDate;
String EventRegTime;

EventUnixTime = eventData.getEventUnixtimeTime();//Returns unixtime of event in seconds
EventUnixTimeMilli = EventUnixTime * 1000; //convert to milliseconds

String timezone = "US/Mountain";
Calendar.setTimeZone(TimeZone timezone);
Date EventDate = new Date(EventUnixTimeMilli);
SimpleDateFormat EventDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat EventTimeFormatter = new SimpleDateFormat("HHMM");

// set strings to use when setting text views
EventRegDate = EventDateFormatter.format(EventDate);
EventRegTime = EventTimeFormatter.format(EventDate);
Это было полезно?

Решение

After playing around some more I figured it out.

long EventUnixTime = eventData.getEventUnixtimeTime();
long EventUnixTimeMilli = (EventUnixTime *1000);

Date EventDate= new Date(EruptionUnixTimeMilli);

SimpleDateFormat EventDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
EventDateFormatter.setTimeZone(TimeZone.getTimeZone("US/Mountain"));

SimpleDateFormat EventTimeFormatter = new SimpleDateFormat("HHMM");
EventTimeFormatter.setTimeZone(TimeZone.getTimeZone("US/Mountain"));

String EventRegDate = EventDateFormatter.format(EventDate);
String EventRegTime = EventTimeFormatter.format(EventDate);

This outputs two strings one that is YYYY-MM-DD and one that is HHMM always in Mountain Time.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top