Android 将整数时间戳转换为人类日期时间

Android convert int timestamp to human datetime

嗨,我有一个 android 应用程序,它使用 webRequestreturn 类型为 Int(或 Long)的时间戳,我想将其转换为人类 reader 日期时间(根据到设备时区)

例如 1175714200 转换为 GMT:2007 年 4 月 4 日,星期三 19:16:40 GMT 您所在的时区:2007 年 4 月 5 日 3:16:40 AM GMT+8:00

我已经使用此函数进行转换,但似乎不 return 正确的结果(所有结果都像 (15/01/1970 04:04:25) 这是不正确的

time.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").
                format(new Date(topStory.getTime() * 1000)));

上面的代码有什么问题吗?

我也有警告信息:

要获取本地格式,请使用 getDateInstance()、getDateTimeInstance() 或 getTimeInstance(),或使用新的 SimpleDateFormat(String template, Locale locale),例如 Locale.US 用于 ASCII 日期。少... (Ctrl+F1) 几乎所有调用者都应该使用 getDateInstance()、getDateTimeInstance() 或 getTimeInstance() 来获取适合用户区域设置的 SimpleDateFormat 的现成实例。您直接 class 创建一个实例的主要原因是因为您需要 format/parse 一种特定的机器可读格式,在这种情况下,您几乎肯定想明确要求我们确保您得到ASCII 数字(而不是阿拉伯数字)。

topStory 是这段代码中的日历实例吗? 乘以1000的目的是什么? 尝试用 Calendar.getInstance() 替换它并删除 * 1000 以调试和检查您的输出。 如果是当前时间,那么不是格式问题,而是您的输入问题。

警告很可能只是因为您的输入不是建议的 类(如 Calendar)之一的实例。

试试这个功能:

private String formatDate(long milliseconds) /* This is your topStory.getTime()*1000 */ {
    DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliseconds);
    TimeZone tz = TimeZone.getDefault();
    sdf.setTimeZone(tz);
    return sdf.format(calendar.getTime());
}

它从正在使用它的设备获取默认时区。如果你有questions/doubts,请评论。此外,此函数将自上一个纪元以来的毫秒数作为输入。如果那不是您的 topStory.getTime() returning 的内容,则此功能将不起作用。在这种情况下,您需要将 topStory.getTime() 的 return 值转换为自上一个纪元以来的毫秒数。

我一直使用这个 SimpleDateFormat,所以这是我使用的代码

public static String dateToString(Date date, String format) {

    SimpleDateFormat formatter = new SimpleDateFormat(format);  
    return formatter.format(date);      

}

我只是从我的上下文中这样称呼它

dateToString(new Date(), "dd_MM_yyyy_HH_mm");

小心使用斜杠 / 或 \ ... 通常会用其他含义混淆您的格式。 new Date() 生成您当前时间的新实例,因此无需 format()

中的数学运算

取自日期 | Android 开发者网站

Date() Initializes this Date instance to the current time.

Date(long milliseconds) Initializes this Date instance using the specified millisecond value.

编辑:如果不需要当前时间,请使用 GregorianCalendar 对象!

GregorianCalendar(int year, int month, int day) Constructs a new GregorianCalendar initialized to midnight in the default TimeZone and Locale on the specified date.

然后使用

GregorianCalendar cal = new GregorianCalendar(2001,11,25);
cal.add(GregorianCalendar.MONTH,2);
cal.get(GregorianCalendar.YEAR); //Returns 2002
cal.get(GregorianCalendar.MONTH); //Returns 1
cal.get(GregorianCalendar.DATE); //Returns 25

如果 topStory.getTime() returns 一个整数(而不是一个长整数)乘以 1000 可能会溢出整数范围。

要解决这个问题,强制使用长数字计算乘法:

topStory.getTime() * 1000L
long DateInLong = 1584212400;
Date date = new Date(DateInLong * 1000L);
SimpleDateFormat simpledateformate = new SimpleDateFormat("yyyy-MM-dd");
String DATE = simpledateformate.format(date);