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

Java 将当前时间(dt)从秒转换为实时格式(小时和分钟),java,android,api,datetime,retrofit,Java,Android,Api,Datetime,Retrofit,我能够通过JSON响应在我的应用程序上显示一些天气数据,但是当前时间(dt)、日出和日落在我的文本视图上显示为秒,即1612730263。 因此,我需要将时间转换为实时格式(小时和分钟),例如晚上9:30免责声明: 而且对我不起作用,因为我的响应来自API。因此,我的问题并非重复 我的API回应: { "lat":9.0765, "lon":7.3986, "timezone":"Africa/Lag

我能够通过JSON响应在我的应用程序上显示一些天气数据,但是当前时间(dt)、日出和日落在我的文本视图上显示为秒,即1612730263。 因此,我需要将时间转换为实时格式(小时和分钟),例如晚上9:30免责声明: 而且对我不起作用,因为我的响应来自API。因此,我的问题并非重复

我的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"
         }
      ]
   }
}
我在家庭活动中的改装呼叫时间:

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()));
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");
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;
    }

}
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;
    }
}
Current.java

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()));
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");
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;
    }

}
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;
    }
}
当前公共类{
@序列化名称(“dt”)
@暴露
私有整数dt;
@序列化名称(“日出”)
@暴露
私人整数日出;
@序列化名称(“日落”)
@暴露
私人整数日落;
@序列化名称(“临时”)
@暴露
私人双温;
@序列化名称(“感觉像”)
@暴露
私人的双重感觉;
@序列化名称(“压力”)
@暴露
私人整数压力;
@序列化名称(“湿度”)
@暴露
私人整数湿度;
@序列化名称(“露点”)
@暴露
私人双露点;
@序列化名称(“uvi”)
@暴露
私人双uvi;
@序列化名称(“云”)
@暴露
私有整数云;
@序列化名称(“可见性”)
@暴露
私有整数可见性;
@序列化名称(“风速”)
@暴露
私人双风速;
@序列化名称(“风度”)
@暴露
私有整数windDeg;
@序列化名称(“天气”)
@暴露
私有列表天气=空;
公共整数getDt(){
返回dt;
}
公共void setDt(整数dt){
这1.dt=dt;
}
公共整数getSunrise(){
回归日出;
}
公共void setunrise(整数日出){
这个。日出=日出;
}
公共整数getSunset(){
回归夕阳;
}
公共无效设置未设置(整数日落){
日落=日落;
}
公共双getTemp(){
返回温度;
}
公共无效设置(双临时){
this.temp=temp;
}
公共双getFeelsLike(){
回归的感觉;
}
公共无效设置feelsLike(双feelsLike){
this.feelsLike=feelsLike;
}
公共整数getPressure(){
回流压力;
}
公共空隙设定压力(整定压力){
这个。压力=压力;
}
公共整数{
返回湿度;
}
公共空间设置湿度(整数湿度){
这个。湿度=湿度;
}
公共双getDewPoint(){
返回露点;
}
公共真空设定露点(双露点){
这个。露点=露点;
}
公共双getUvi(){
返回uvi;
}
公共无效设置uvi(双uvi){
this.uvi=uvi;
}
公共整数getClouds(){
回归云;
}
公共云(整型云){
云=云;
}
公共整数getVisibility(){
返回能见度;
}
公共void集合可见性(整数可见性){
这个.可见性=可见性;
}
公共双getWindSpeed(){
返回风速;
}
公共空间设置风速(双风速){
this.windSpeed=风速;
}
公共整数getWindDeg(){
返回风度;
}
公共void setWindDeg(整数windDeg){
这是windDeg=windDeg;
}
公共列表getWeather(){
回归天气;
}
公众天气(列出天气){
这个天气=天气;
}
}

请我需要提供的代码链接到我的应用程序,以便更容易实现它。我有dt转换的基本知识,但不是来自天气API响应。我认为使用我的文本视图转换数据会更好(如果有任何方法可以使用我的文本视图进行转换)

只需创建一个日期对象,并将该值作为参数:

java.util.Date time=new java.util.Date(((长)时间戳)*1000);

由于java希望将毫秒作为参数,因此需要将值(以秒为单位)乘以1000。

只需创建一个日期对象,并将该值作为参数:

java.util.Date time=new java.util.Date(((长)时间戳)*1000);
由于java期望毫秒作为参数,您需要将值(以秒为单位)乘以1000。

您可以使用来获取
即时
,您可以将其转换为指定时区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();
    }
}
输出:

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
了解有关现代日期时间API的更多信息

无论出于何种原因,如果您必须坚持使用Java6或Java7,您可以使用哪个backport将大部分Java.time功能移植到Java6&7。如果您正在为Android项目工作,并且您的Android API级别仍然不符合Java-8,选中并。

您可以使用来获取
即时
,您可以将其转换为指定时区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();
    }
}
输出:

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
了解有关现代日期时间API的更多信息

无论出于何种原因,如果您必须坚持使用Java6或Java7,您可以使用哪个backport将大部分Java.time功能移植到Java6&7。如果您正在为Android项目工作,并且您的Android API级别仍然不符合Java-8,请检查并重试。

String timezone=“Africa/Lagos”//“时区”:“非洲/拉各斯”
长dt=1612779720L;//“dt”:1612779720
长时间=1612763455L;//《日出》:1612763455
长日落时间=1612805901L;//“日落”:1612805901
双温=304.15D;//“温度”:304.15(单位:开尔文)。
SimpleDataFormat sdf=新的简单化