繁体   English   中英

Java遍历日期对象的arraylist并将每个日期转换为其unix时间戳

[英]Java Iterate through arraylist of date objects and convert each date to its unix time stamp

我有一个日期对象的数组列表,我想将其转换为每个日期的Unix时间戳。 如何才能做到这一点?

在Java 8+中,您可以流式传输List并将时间从Date.getTime()映射到时间戳,方法是除以1000(因为unix时间戳以自纪元开始的秒数表示,而Java时间戳以纪元为纪元)。 然后将其收集到List<Long>

List<Date> dates = new ArrayList<>();
// ...
List<Long> unixTimeStamps = dates.stream()
        .mapToLong(x -> x.getTime() / 1000).boxed()
        .collect(Collectors.toList());

Date类具有方法getTime() ,该方法检索自1970年1月1日以来的毫秒数。您可以使用此方法,并将其除以1000就可以得到Unix Time

List<Date> dates = new ArrayList<>();

//...
//populate `date` using suitable logic
//...

List<Long> unixTS = new ArrayList<>();
for(Date date : dates) {
    unixTS.add(date.getTime()/1000);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM