简体   繁体   English

将当前时间(dt)从秒转换为实时格式(小时和分钟)

[英]Convert current time(dt) from seconds to real time format(hour and minute)

I was able to display some weather data on my app using retrofit from a JSON response, but the current time(dt), sunrise, and sunset displays on my textviews as seconds ie 1612730263. So I need to convert the time to a real-time format(hour and minute) eg 9:30 PM.我能够使用来自 JSON 响应的 retrofit 在我的应用程序上显示一些天气数据,但是当前时间(dt)、日出和日落在我的 textviews 上显示为秒,即 1612730263。所以我需要将时间转换为真实时间时间格式(小时和分钟),例如晚上 9:30。 Disclaimer : Java: Date from unix timestamp and How to convert seconds to time format?免责声明Java:来自 unix 时间戳的日期以及如何将秒转换为时间格式? doesn't work for me because my response is from an API.对我不起作用,因为我的回复来自 API。 Therefore my question is not a duplicate.因此我的问题不是重复的。

My API response:我的 API 响应:

    {
   "lat":9.0765,
   "lon":7.3986,
   "timezone":"Africa/Lagos",
   "timezone_offset":3600,
   "current":{
      "dt":1612779720,
      "sunrise":1612763455,
      "sunset":1612805901,
      "temp":304.15,
      "feels_like":302.14,
      "pressure":1013,
      "humidity":33,
      "dew_point":286,
      "uvi":8.42,
      "clouds":42,
      "visibility":7000,
      "wind_speed":4.12,
      "wind_deg":100,
      "weather":[
         {
            "id":802,
            "main":"Clouds",
            "description":"scattered clouds",
            "icon":"03d"
         }
      ]
   }
}

My Retrofit call for the time in HomeActivity :我的 Retrofit 呼叫HomeActivity的时间:

Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrl).addConverterFactory(GsonConverterFactory.create()).build();
        WeatherService service = retrofit.create(WeatherService.class);
        Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, AppId);
        call.enqueue(new Callback<WeatherResponse>() {

            @Override
            public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {
                if (response.code() == 200) {
                    WeatherResponse weatherResponse = response.body();
                    assert weatherResponse != null;

                    assert response.body() != null;
// current time textview
                  time_field.setText(String.valueOf(response.body().getCurrent().getDt()));

My Retrofit call for the time & in FirstFragment :我的 Retrofit 呼叫时间和FirstFragment

Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrl).addConverterFactory(GsonConverterFactory.create()).build();
                WeatherService service = retrofit.create(WeatherService.class);
                Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, AppId);
                call.enqueue(new Callback<WeatherResponse>() {
                    @Override
                    public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {
                        if (response.code() == 200) {
                            WeatherResponse weatherResponse = response.body();
                            assert weatherResponse != null;

                            assert response.body() != null; 
// sunrise & sunset time textviews                                                             
rise_time.setText(response.body().getCurrent().getSunrise() + " AM");                                
set_time.setText(response.body().getCurrent().getSunset() + " PM");

EDIT编辑

WeatherResponse.java : WeatherResponse.java

public class WeatherResponse {

    @SerializedName("lat")
    @Expose
    private Double lat;
    @SerializedName("lon")
    @Expose
    private Double lon;
    @SerializedName("timezone")
    @Expose
    private String timezone;
    @SerializedName("timezone_offset")
    @Expose
    private Integer timezoneOffset;
    @SerializedName("current")
    @Expose
    private Current current;

    public Double getLat() {
        return lat;
    }

    public void setLat(Double lat) {
        this.lat = lat;
    }

    public Double getLon() {
        return lon;
    }

    public void setLon(Double lon) {
        this.lon = lon;
    }

    public String getTimezone() {
        return timezone;
    }

    public void setTimezone(String timezone) {
        this.timezone = timezone;
    }

    public Integer getTimezoneOffset() {
        return timezoneOffset;
    }

    public void setTimezoneOffset(Integer timezoneOffset) {
        this.timezoneOffset = timezoneOffset;
    }

    public Current getCurrent() {
        return current;
    }

    public void setCurrent(Current current) {
        this.current = current;
    }

}

Current.java :当前.java

public class Current {

    @SerializedName("dt")
    @Expose
    private Integer dt;
    @SerializedName("sunrise")
    @Expose
    private Integer sunrise;
    @SerializedName("sunset")
    @Expose
    private Integer sunset;
    @SerializedName("temp")
    @Expose
    private Double temp;
    @SerializedName("feels_like")
    @Expose
    private Double feelsLike;
    @SerializedName("pressure")
    @Expose
    private Integer pressure;
    @SerializedName("humidity")
    @Expose
    private Integer humidity;
    @SerializedName("dew_point")
    @Expose
    private Double dewPoint;
    @SerializedName("uvi")
    @Expose
    private Double uvi;
    @SerializedName("clouds")
    @Expose
    private Integer clouds;
    @SerializedName("visibility")
    @Expose
    private Integer visibility;
    @SerializedName("wind_speed")
    @Expose
    private Double windSpeed;
    @SerializedName("wind_deg")
    @Expose
    private Integer windDeg;
    @SerializedName("weather")
    @Expose
    private List<Weather> weather = null;

    public Integer getDt() {
        return dt;
    }

    public void setDt(Integer dt) {
        this.dt = dt;
    }

    public Integer getSunrise() {
        return sunrise;
    }

    public void setSunrise(Integer sunrise) {
        this.sunrise = sunrise;
    }

    public Integer getSunset() {
        return sunset;
    }

    public void setSunset(Integer sunset) {
        this.sunset = sunset;
    }

    public Double getTemp() {
        return temp;
    }

    public void setTemp(Double temp) {
        this.temp = temp;
    }

    public Double getFeelsLike() {
        return feelsLike;
    }

    public void setFeelsLike(Double feelsLike) {
        this.feelsLike = feelsLike;
    }

    public Integer getPressure() {
        return pressure;
    }

    public void setPressure(Integer pressure) {
        this.pressure = pressure;
    }

    public Integer getHumidity() {
        return humidity;
    }

    public void setHumidity(Integer humidity) {
        this.humidity = humidity;
    }

    public Double getDewPoint() {
        return dewPoint;
    }

    public void setDewPoint(Double dewPoint) {
        this.dewPoint = dewPoint;
    }

    public Double getUvi() {
        return uvi;
    }

    public void setUvi(Double uvi) {
        this.uvi = uvi;
    }

    public Integer getClouds() {
        return clouds;
    }

    public void setClouds(Integer clouds) {
        this.clouds = clouds;
    }

    public Integer getVisibility() {
        return visibility;
    }

    public void setVisibility(Integer visibility) {
        this.visibility = visibility;
    }

    public Double getWindSpeed() {
        return windSpeed;
    }

    public void setWindSpeed(Double windSpeed) {
        this.windSpeed = windSpeed;
    }

    public Integer getWindDeg() {
        return windDeg;
    }

    public void setWindDeg(Integer windDeg) {
        this.windDeg = windDeg;
    }

    public List<Weather> getWeather() {
        return weather;
    }

    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }
}

Please I need the code provided to be linked to my app so that it will be easier to implement it.请我需要提供的代码链接到我的应用程序,以便更容易实现它。 I have basic knowledge of dt conversion, but not from a weather API response.我有 dt 转换的基本知识,但不是来自天气 API 响应。 I think using my textviews to convert the data will be better(If there's any way you can use my textviews to do it)我认为使用我的文本视图来转换数据会更好(如果有任何方法可以使用我的文本视图来做到这一点)

It seems you need to obtain the right date patterns right from the information returned in the WeatherResponse and related classes.您似乎需要从WeatherResponse和相关类中返回的信息中获取正确的日期模式。

For this purpose, you need to customize the Gson library you are using in your code to deserialize the information returned by the openweathermap API by Retrofit.为此,您需要自定义您在代码中使用的 Gson 库,以反序列化 ZB9794896D699A78542122D376A03C005 的 openweathermap API 返回的信息。

There are several ways to do this but, as far as you have the ability to modify the classes generated by jsonschema2pojo , I would suggest the following approach.有几种方法可以做到这一点,但只要您有能力修改jsonschema2pojo生成的类,我建议采用以下方法。

The idea consists basically in implement a custom Gson deserializer to handle the required transformation.这个想法基本上包括实现一个自定义 Gson 解串器来处理所需的转换。

You can opt for implement this custom deserializer for the whole Current class but I think it will be easier to only handle the deserialization of the necessary fields.您可以选择为整个Current class 实施此自定义反序列化器,但我认为只处理必要字段的反序列化会更容易。

For that purpose, first, let's create a new type;为此,首先,让我们创建一个新类型; it will serve as a marker for the fields that require the custom deserialization.它将作为需要自定义反序列化的字段的标记。 For example:例如:

public class PrettyTime {

  private String value;

  public PrettyTime() {
  }

  public PrettyTime(String value) {
    this.value = value;
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return getValue();
  }
}

Apply this marker to the fields you need the conversion in the Current class:将此标记应用于Current class 中需要转换的字段:

public class Current {

  @SerializedName("dt")
  @Expose
  private PrettyTime dt;
  @SerializedName("sunrise")
  @Expose
  private PrettyTime sunrise;
  @SerializedName("sunset")
  @Expose
  private PrettyTime sunset;

  // The rest of the fields and setters and getters

  public PrettyTime getDt() {
    return dt;
  }

  public void setDt(PrettyTime dt) {
    this.dt = dt;
  }

  public PrettyTime getSunrise() {
    return sunrise;
  }

  public void setSunrise(PrettyTime sunrise) {
    this.sunrise = sunrise;
  }

  public PrettyTime getSunset() {
    return sunset;
  }

  public void setSunset(PrettyTime sunset) {
    this.sunset = sunset;
  }
  
}

Next, let's create the custom deserializer:接下来,让我们创建自定义反序列化器:

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PrettyTimeDeserializer implements JsonDeserializer<PrettyTime> {
  // Modify the date pattern as you consider appropriate
  private static final SimpleDateFormat HMM = new SimpleDateFormat("hh:mm");

  public PrettyTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    final long seconds = json.getAsJsonPrimitive().getAsLong();
    final Date date = new Date(seconds * 1000);
    final String prettyFormatted = HMM.format(date);
    return new PrettyTime(prettyFormatted);
  }
}

Finally, integrate this deserializer in your code, both in the HomeActivity and FirstFragment classes:最后,将此反序列化器集成到您的代码中,包括HomeActivityFirstFragment类:

Gson gson = new GsonBuilder()
  .registerTypeAdapter(PrettyTime.class, new PrettyTimeDeserializer())
  .create();

Retrofit retrofit = new Retrofit.Builder()
  .baseUrl(BaseUrl)
  // Please note the gson argument
  .addConverterFactory(GsonConverterFactory.create(gson))
  .build()
;

// The rest of your code

Just create a date object with that value as parameter:只需使用该值作为参数创建一个日期 object :

java.util.Date time=new java.util.Date(((long)timeStamp)*1000);

As java is expecting milliseconds as a parameter, you need to multiply your value (in seconds) by 1000.由于 java 期望毫秒作为参数,因此您需要将值(以秒为单位)乘以 1000。

You can use Instant#ofEpochSecond to get the Instant which you can convert into ZonedDateTime for the specified timezone ID and then format the obtained ZonedDateTime using DateTimeFormatter .您可以使用Instant#ofEpochSecond获取Instant ,您可以将其转换为指定时区 ID 的ZonedDateTime ,然后使用DateTimeFormatter格式化获得的ZonedDateTime

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(
                "Sunrise date and time with timezone: " + getDateTimeWithTzString(1608529251L, "Africa/Lagos"));
        System.out.println("Sunrise date and time: " + getDateTimeString(1608529251L, "Africa/Lagos"));
        System.out.println("Sunrise time: " + getTimeString(1608529251L, "Africa/Lagos"));
        System.out.println("Date: " + getDateString(1608529251L, "Africa/Lagos"));
    }

    static String getDateTimeWithTzString(long epochSecond, String strTz) {
        ZoneId zoneId = ZoneId.of(strTz);
        Instant instant = Instant.ofEpochSecond(epochSecond);
        ZonedDateTime zdt = instant.atZone(zoneId);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd h:m:s a '['VV']'", Locale.ENGLISH);
        return zdt.format(dtf);
    }

    static String getDateTimeString(long epochSecond, String strTz) {
        ZoneId zoneId = ZoneId.of(strTz);
        Instant instant = Instant.ofEpochSecond(epochSecond);
        ZonedDateTime zdt = instant.atZone(zoneId);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd h:m:s a", Locale.ENGLISH);
        return zdt.format(dtf);
    }

    static String getTimeString(long epochSecond, String strTz) {
        ZoneId zoneId = ZoneId.of(strTz);
        Instant instant = Instant.ofEpochSecond(epochSecond);
        ZonedDateTime zdt = instant.atZone(zoneId);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:m:s a", Locale.ENGLISH);
        return zdt.format(dtf);
    }

    static String getDateString(long epochSecond, String strTz) {
        ZoneId zoneId = ZoneId.of(strTz);
        Instant instant = Instant.ofEpochSecond(epochSecond);
        ZonedDateTime zdt = instant.atZone(zoneId);
        return zdt.toLocalDate().toString();
    }
}

Output: Output:

Sunrise date and time with timezone: 2020-12-21 6:40:51 AM [Africa/Lagos]
Sunrise date and time: 2020-12-21 6:40:51 AM
Sunrise time: 6:40:51 AM
Date: 2020-12-21

Learn more about the modern date-time API from Trail: Date Time .Trail: Date Time了解有关现代日期时间 API 的更多信息。

For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project . For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level仍然不符合 Java-8,检查Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project

String timezone = "Africa/Lagos"; // "timezone":"Africa/Lagos"
long dt = 1612779720L; // "dt":1612779720
long sunriseTime = 1612763455L; // "sunrise":1612763455
long sunsetTime = 1612805901L; // "sunset":1612805901
double temp = 304.15D; // "temp":304.15 (in Kelvin).
        
SimpleDateFormat sdf = new SimpleDateFormat("h:mm aa"); // h:mm AM/PM (hh:mm aa == hh:mm AM/PM).
sdf.setTimeZone(TimeZone.getTimeZone(timezone));
        
// current local time
String time = sdf.format(new Date(dt));
// sunrise
String sunrise = sdf.format(new Date(sunriseTime));
// sunset
String sunset = sdf.format(new Date(sunsetTime));
// temperature in Celcius
String celcius = String.format("%.2f °C", temp - 273.16D);
// temperature in Fahrenheit
String fahrenheit = String.format("%.2f °F", ((temp - 273D) * 9D/5D) + 32D);
        
System.out.println(time); //4:59 PM
System.out.println(sunrise); //4:59 PM
System.out.println(sunset); //5:00 PM
System.out.println(celcius); //30.99 °C
System.out.println(fahrenheit); //88.07 °F

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM