【问题标题】:How to convert Timestamp to Date and calculate to "time ago"?如何将时间戳转换为日期并计算为“时间前”?
【发布时间】:2019-11-24 14:22:16
【问题描述】:

我在 mysql 服务器上有一个时间戳。示例:“2019-11-23 14:26:11”。我从服务器获得了一个字符串形式的时间戳,根据我的想法,我应该将时间戳转换为日期,然后计算“时间前”。请帮忙

【问题讨论】:

  • 您使用哪个网络库?好的http?改造?
  • @Fartab 我用 Volley

标签: java android kotlin timestamp


【解决方案1】:

我认为这个已回答的问题也解决了你的问题。

Android difference between Two Dates

将您的字符串从服务器转换为 Date 对象,然后减去当前日期 - 您从服务器获得的内容。

获取当前日期:

import java.util.Calendar

Date currentTime = Calendar.getInstance().getTime();

【讨论】:

    【解决方案2】:

    使用此方法返回时间前的文本 setTime(Integer.valueOf(time_stamp));

    private String setTime(int date) {
            String time_text = "";
            long time = System.currentTimeMillis() / 1000;
    
            long mills = time - date;
            int hours = safeLongToInt(mills / (60 * 60));
            int mins = safeLongToInt((mills - (hours * 3600) / (60)) % 60);
    
            String diff = hours + ":" + mins;
    
            if (hours < 24) {
                duration.setText(diff + " hours ago");
            } else {
                Date dateTemp = new Date(date * 1000L);
    
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss ");
    
                sdf.setTimeZone(getTimeZone("GMT+2"));
                time_text = sdf.format(dateTemp);
    
                return time_text;
    
            }
            return time_text;
        }
    

    【讨论】:

    • setTime(Integer.valueOf(time_stamp)); 你认为Integer.valueOf("2019-11-23 14:26:11") 会返回什么?
    • 对不起,我没有注意到我以为你的意思是 Unix 时间戳
    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 2016-11-26
    • 2017-04-25
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多