Get only the date from the timestamp(仅从时间戳中获取日期)

本文介绍了仅从时间戳中获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我传递时间戳的下面函数,我只需要从时间戳返回的日期,而不是小时和秒.使用下面的代码,我得到-

This is my Below function in which I am passing timestamp, I need only the date in return from the timestamp not the Hours and Second. With the below code I am getting-

private String toDate(long timestamp) {
        Date date = new Date (timestamp * 1000);
        return DateFormat.getInstance().format(date).toString();
}

这是我得到的输出.

11/4/01 11:27 PM

但我只需要这样的日期

2001-11-04

有什么建议吗?

推荐答案

改用 SimpleDateFormat:

Use SimpleDateFormat instead:

private String toDate(long timestamp) {
    Date date = new Date(timestamp * 1000);
    return new SimpleDateFormat("yyyy-MM-dd").format(date);
}

更新:Java 8 解决方案:

Updated: Java 8 solution:

private String toDate(long timestamp) {
    LocalDate date = Instant.ofEpochMilli(timestamp * 1000).atZone(ZoneId.systemDefault()).toLocalDate();
    return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}

这篇关于仅从时间戳中获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!