我在将时间戳转换为 android 中的日期和时间时遇到问题?
I have problem to convert timestamp to date and time in android?
您好,当我使用此代码将时间戳转换为日期时。但我不知道我什么时候输入日期现在年份时间戳以获得它打印 1970 年的时间。
你能帮帮我吗?
我使用的代码:
Date a = new Date(1586822400);
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String d = simpleDateFormat.format(date);
但是:
Date date = new Date(1586822400L*1000L);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String strDate = simpleDateFormat.format(date);
您需要乘以 1000L 将 unix 秒转换为毫秒;
请勿使用outdated date/time API. Do it using the modern date/time API如下:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Using Instant.ofEpochMilli
LocalDate date = Instant.ofEpochMilli(1586822400 * 1000L).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date));
// Directly using Instant.ofEpochSecond
date = Instant.ofEpochSecond(1586822400).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date));
}
}
输出:
2020/04/14
2020/04/14
您好,当我使用此代码将时间戳转换为日期时。但我不知道我什么时候输入日期现在年份时间戳以获得它打印 1970 年的时间。 你能帮帮我吗?
我使用的代码:
Date a = new Date(1586822400);
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String d = simpleDateFormat.format(date);
但是:
Date date = new Date(1586822400L*1000L);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String strDate = simpleDateFormat.format(date);
您需要乘以 1000L 将 unix 秒转换为毫秒;
请勿使用outdated date/time API. Do it using the modern date/time API如下:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Using Instant.ofEpochMilli
LocalDate date = Instant.ofEpochMilli(1586822400 * 1000L).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date));
// Directly using Instant.ofEpochSecond
date = Instant.ofEpochSecond(1586822400).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date));
}
}
输出:
2020/04/14
2020/04/14