Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Formatting time

Hi, how could I format time for sunrise/sunset Label's ? Getting result: 1475814804

----------------------MainActivity.java------------------------------

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this);

    mProgressBar.setVisibility(View.INVISIBLE);

    final double latitude = 54.8487974;
    final double longitude = 25.4712113;

    mRefreshImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getForecast(latitude, longitude);
        }
    });

    getForecast(latitude, longitude);

    Log.d(TAG, "Main UI code is running!");
}

private void getForecast(double latitude, double longitude) {
    String apiKey = "d22fdf8d7f9e52b0dfc3f871c2e3146a";
    String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
            "/" + latitude + "," + longitude + "?units=si";


    if (isNetworkAvailable()) {
        toggleRefresh();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(forecastUrl)
                .build();


        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toggleRefresh();
                    }
                });
                alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toggleRefresh();
                    }
                });

                try {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mForecast = parseForecastDetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateDisplay();
                            }
                        });
                    } else {
                        alertUserAboutError();
                    }
                }
                catch (IOException e) {
                    Log.e(TAG, "Exception caught: ", e);
                }
                catch (JSONException e) {
                    Log.e(TAG, "Exception caught: ", e);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    else {
        Toast.makeText(this, getString(R.string.network_unavailable_message),
                Toast.LENGTH_LONG).show();
    }
}

private void toggleRefresh() {
    if (mProgressBar.getVisibility() == View.INVISIBLE) {
        mProgressBar.setVisibility(View.VISIBLE);
        mRefreshImageView.setVisibility(View.INVISIBLE);
    }
    else {
        mProgressBar.setVisibility(View.INVISIBLE);
        mRefreshImageView.setVisibility(View.VISIBLE);
    }
}

private void updateDisplay() {
    Current current = mForecast.getCurrent();




    mTemperatureLabel.setText(current.getTemperature() + "");

    mHumidityValue.setText(current.getHumidity() + "");
    mPrecipValue.setText(current.getPrecipChance() + "%");
    mSummaryLabel.setText(current.getSummary());

    mSunsetLabel.setText(String.valueOf(list.get(0).sunsetTime));
    mSunriseLabel.setText(String.valueOf(list.get(0).sunriseTime));


    Drawable drawable = getResources().getDrawable(current.getIconId());
    mIconImageView.setImageDrawable(drawable);
}

    private Forecast parseForecastDetails (String jsonData) throws Exception {
        Forecast forecast = new Forecast();

        forecast.setCurrent(getCurrentDetails(jsonData));
        forecast.setHourlyForecast(getHourlyForecast(jsonData));
        forecast.setDailyForecast(getDailyForecast(jsonData));

        return forecast;
    }

private Day[] getDailyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject daily = forecast.getJSONObject("daily");
    JSONArray data = daily.getJSONArray("data");

    Day[] days = new Day[data.length()];

    for (int i=0; i < data.length(); i++) {
        JSONObject jsonDay = data.getJSONObject(i);
        Day day = new Day();

        day.setSummary(jsonDay.getString("summary"));
        day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
        day.setIcon(jsonDay.getString("icon"));
        day.setTime(jsonDay.getLong("time"));
        day.setTimezone(timezone);



        days[i] = day;
    }

    return days;
}

private Hour[] getHourlyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject hourly = forecast.getJSONObject("hourly");
    JSONArray data = hourly.getJSONArray("data");

    Hour[] hours = new Hour[data.length()];

    for (int i=0; i < data.length(); i++) {
        JSONObject jsonHour = data.getJSONObject(i);
        Hour hour = new Hour();

        hour.setSummary(jsonHour.getString("summary"));
        hour.setIcon(jsonHour.getString("icon"));
        hour.setTemperature(jsonHour.getDouble("temperature"));
        hour.setTime(jsonHour.getLong("time"));
        hour.setTimezone(timezone);
        hours[i] = hour;
    }

            return hours;
}

List<Data> list = new ArrayList<>();

private Current getCurrentDetails(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);

    String timezone = forecast.getString("timezone");
    Log.i(TAG, "From JSON: " + timezone);

    JSONObject currently = forecast.getJSONObject("currently");
    JSONObject daily = forecast.getJSONObject("daily");
    JSONArray data = daily.getJSONArray("data");




    for(int k = 0; k < data.length(); k++) {




        JSONObject item = data.getJSONObject(k);
        Data d = new Data();

        d.sunsetTime = item.getLong("sunsetTime");
        d.sunriseTime = item.getLong("sunriseTime");




        list.add(d);
    }


    Current current = new Current();


    current.setHumidity(currently.getDouble("humidity"));
    current.setTime(currently.getLong("time"));
    current.setIcon(currently.getString("icon"));
    current.setPrecipChance(currently.getDouble("precipProbability"));
    current.setSummary(currently.getString("summary"));
    current.setTemperature(currently.getDouble("temperature"));
    current.setTimeZone(timezone);

    Log.d(TAG, current.getFormattedTime());

    return current;
}



static class Data {

    long sunsetTime;
    long sunriseTime;
    @Override

    public String toString() {
         return "Data{" +

                ", sunsetTime=" + sunsetTime +
                ", sunriseTime=" + sunriseTime +
                '}';

    }
}


private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }

    return isAvailable;
}

private void alertUserAboutError() {
    AlertDialogFragment dialog = new AlertDialogFragment();
    dialog.show(getFragmentManager(), "error_dialog");
}

@OnClick (R.id.dailyButton)
public void startDailyActivity (View view) {
    Intent intent = new Intent(this, DailyForecastActivity.class);
    intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
    startActivity(intent);
}

@OnClick (R.id.hourlyButton)
public void startHourlyActivity (View view) {
    Intent intent = new Intent(this, HourlyForecastActivity.class);
    intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
    startActivity(intent);
}

}

-------------------------------------Current.java----------------------------------- public class Current { private String mIcon; private long mTime; private double mTemperature; private double mHumidity; private double mPrecipChance; private String mSummary; private String mTimeZone;

public String getTimeZone() {
    return mTimeZone;
}

public void setTimeZone(String timeZone) {
    mTimeZone = timeZone;
}

public String getIcon() {
    return mIcon;
}

public void setIcon(String icon) {
    mIcon = icon;
}

public int getIconId() {
    return Forecast.getIconId(mIcon);
}

public long getTime() {
    return mTime;
}


public String getFormattedTime() {
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
    formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone()));
    Date dateTime = new Date(getTime() * 1000);
    String timeString = formatter.format(dateTime);

    return timeString;
}

public void setTime(long time) {
    mTime = time;
}

public int getTemperature() {
    return (int)Math.round(mTemperature);
}

public void setTemperature(double temperature) {
    mTemperature = temperature;
}

public double getHumidity() {
    return mHumidity;
}

public void setHumidity(double humidity) {
    mHumidity = humidity;
}



public int getPrecipChance() {
    double precipPercentage = mPrecipChance * 100;
    return (int)Math.round(precipPercentage);
}

public void setPrecipChance(double precipChance) {
    mPrecipChance = precipChance;
}

public String getSummary() {
    return mSummary;
}

public void setSummary(String summary) {
    mSummary = summary;
}

}

1 Answer

new SimpleDateFormat("HH:mm").format(new Date(sunriseTime)))

See this page for further formatting options.