java - 如何从长日期获取年月日?
问题描述
如何从“dd/MM/yyyy”格式的长日期中提取年月日。
long date = a.creationDate;
SimpleDateFormat dateFormatNew = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = dateFormatNew.format(date);
解决方案
如果您想从以毫秒为单位的日期时间中提取年、月和日的单个值,您现在应该使用java.time
它。
看这个例子:
public static void main(String[] args) {
// example millis of "now"
long millis = Instant.now().toEpochMilli(); // use your a.creationDate; here instead
// create an Instant from the given milliseconds
Instant instant = Instant.ofEpochMilli(millis);
// create a LocalDateTime from the Instant using the time zone of your system
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// then print the single parts of that LocalDateTime
System.out.println("Year: " + ldt.getYear()
+ ", Month: " + ldt.getMonthValue()
+ " (" + ldt.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH)
+ "), Day: " + ldt.getDayOfMonth()
+ " (" + ldt.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH)
+ ")");
}
输出是这样的:
Year: 2020, Month: 3 (March), Day: 6 (Friday)
如果您支持低于 26 的 Android API 级别,不幸的是,您将不得不导入一个反向移植库,请阅读此内容以获取说明...
推荐阅读
- sql - 在没有游标的情况下返回数据库中所有表中所有外键的计数 - 在 Postgres 中
- gam - 如何从 mgcv 解释随机效应图
- javascript - 您如何从第三方库中捕获“未捕获(承诺)错误”?
- python - 在 Ubuntu 16.04 LTS 中从 Python 3.5 升级到 Python 3.6 后出现的问题
- c++ - 判断是否存在移动构造函数的特征
- c++ - 为什么在定义自定义点对象时需要删除函数?
- node.js - 与 Express 中的重定向路由异步
- javascript - 如何使用 IF 条件更改 for 循环中的列值
- html - 内容溢出容器并在屏幕缩小时重叠页脚
- postgresql - PostgreSQL 未用于我们数据库的表,查询问题?