java - 转换后日出日落时间相等
问题描述
我正在尝试转换 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 call is done through Nepal
如果这有帮助。为什么时间只有1分钟的差异?谁能帮我
解决方案
java.time 和 ThreeTenABP
很抱歉,我只能编写 Java 代码。我相信你会翻译。为了演示,我正在使用这个片段。
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
在格式模式字符串中。如果您愿意AM
,并且PM
按照英语的惯例,最好指定英语语言环境。
正如评论中所建议的那样,将自纪元以来的秒数乘以 1000 以获得毫秒是可行的,但是像这样进行自己的时间转换是一个坏习惯。虽然乘以 1000 看起来很简单,但它可能已经让阅读您的代码的人感到疑惑,并且这种转换很快就会变得复杂且容易出错。我们有经过充分验证的库方法来执行这些操作,这也使我们的代码能够自我记录:我对该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[Asia/Kathmandu]
日落。正如你所指出的,它们之间只有不到一分钟的时间。
问题:java.time 不需要 Android API 级别 26 吗?
java.time 在较旧和较新的 Android 设备上都能很好地工作。它只需要至少Java 6。
- 在 Java 8 及更高版本以及更新的 Android 设备(从 API 级别 26 开始)中,现代 API 是内置的。
- 在非 Android Java 6 和 7 中获得 ThreeTen Backport,现代类的后向端口(ThreeTen 用于 JSR 310;请参阅底部的链接)。
- 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从
org.threeten.bp
子包中导入日期和时间类。
链接
- Oracle 教程:日期时间解释如何使用 java.time。
- Java 规范请求 (JSR) 310,
java.time
第一次描述的地方。 - ThreeTen Backport 项目,
java.time
Java 6 和 7 的反向移植(ThreeTen for JSR-310)。 - ThreeTenABP , ThreeTen Backport 的 Android 版
- 问题:如何在Android项目中使用ThreeTenABP,有非常详尽的解释。
推荐阅读
- powershell - 如何根据其他参数有条件地设置 PowerShell PSDefaultParameterValues
- node.js - 向 Morgan 和 EcsFormater 记录器添加自定义字段,这在 node.js 中是否可行
- c# - 事件被触发但不改变 UI
- spring - 尝试使用 Spring JPA 发送带有外键的 JSON 对象的 POST 请求时出现重复或 Null 错误
- python - 屏幕抓取特定问题
- amazon-s3 - PySpark 将 str 转换为 TimestampType
- flutter - Flutter:设置 WebView Cookie
- sql - bcp 查询出 XML 文件格式问题
- php - 正则表达式:带排除的点包括排除的字符
- java - max_allowed_packet 变量更改未解析 Packet for query is too large 错误