gpt4 book ai didi

java - 转换后日出和日落时间相等

转载 作者:行者123 更新时间:2023-12-01 19:34:07 24 4
gpt4 key购买 nike

我正在尝试转换 openweathermap 提供的毫秒格式的时间,但是当我转换它们时,时间仅相差 1 分钟。

我尝试使用 Simpledateformat 进行转换。

fun formatTIme(sun:Date):String{
val timeformat:SimpleDateFormat= SimpleDateFormat("h:m a")
return timeformat.format(sun)

}

sys": {
"type": 1,
"id": 9201,
"message": 0.0075,
"country": "NP",
"sunrise": 1571444437,
"sunset": 1571485599
},
"timezone": 20700,
"id": 1282682,
"name": "Thapathali",
"cod": 200
}

API 调用是通过尼泊尔完成的(如果这有帮助的话)。为什么时间只相差1分钟?谁能帮帮我

最佳答案

java.time 和 ThreeTenABP

很抱歉我只能编写Java代码。我相信你能翻译。为了进行演示,我使用此代码 fragment 。

    long sunrise = 1571444437;
long sunset = 1571485599;
System.out.println(formatTime(Instant.ofEpochSecond(sunrise)));
System.out.println(formatTime(Instant.ofEpochSecond(sunset)));

输出是:

6:05 AM
5:31 PM

我已经像这样声明了 formatTime - 它适用于您的 API 级别,请参阅下面的详细信息。

static final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("h:mm a", Locale.ENGLISH)
.withZone(ZoneId.of("Asia/Kathmandu"));

static String formatTime(Instant time) {
return formatter.format(time);
}

我已指定两位数分钟来获取 6:05,这是惯例,而不是 6:5。如果您更喜欢后者,请将格式模式字符串中的 mm 更改为 m。如果您希望按照英语的惯例采用这种方式 AMPM,那么最好指定英语区域设置。

按照评论中的建议,将纪元以来的秒数乘以 1000 以获得毫秒,这是可行的,但是像这样进行自己的时间转换是一个坏习惯。虽然乘以 1000 看起来很简单,但它可能已经让阅读代码的人感到困惑,而且这种转换很快就会变得复杂且容易出错。我们有经过充分验证的库方法来完成这些任务,这也使我们的代码可以 self 记录:我使用的 ofEpochSecond 方法已经表明该数字以秒为单位,并且无需怀疑,我想一切都很清楚。

如果您尚未达到 Android API 级别 26 并且不需要外部依赖项,请使用以下内容进行转换:

    TimeUnit.SECONDS.toMillis(sunrise)

这也更清楚地告诉读者您正在执行从秒到毫秒的转换。

您的代码出了什么问题?

你还没有显示代码哪里出了问题,但我认为从注释中已经很清楚了。当将自纪元以来的秒数视为毫秒时,您会得到 1970-01-19T10:00:44.437+05:30[Asia/Kathmandu] 日出和 1970-01-19T10:01 :25.599+05:30[亚洲/加德满都] 日落。正如您所指出的,它们之间的间隔不到一分钟。

问题:java.time 不需要 Android API 级别 26 吗?

java.time 在旧版和新版 Android 设备上都能很好地工作。它只需要至少 Java 6

  • 在 Java 8 及更高版本以及较新的 Android 设备(从 API 级别 26 开始)中,现代 API 是内置的。
  • 在非 Android Java 6 和 7 中获取 ThreeTen Backport,即现代类的向后移植(ThreeTen for JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保使用子包从 org. Threeten.bp 导入日期和时间类。

链接

关于java - 转换后日出和日落时间相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com