【问题标题】:Android:Message created time is not displayed in timestampAndroid:消息创建时间不显示在时间戳中
【发布时间】:2026-01-30 01:15:01
【问题描述】:

我现在必须在聊天应用程序的时间戳中显示消息创建时间我的所有时间戳它会自动显示设备时间当我打开应用程序时它没有显示消息创建时间。检查我的代码并更改我如果我做错了.

public static String getFormatedTime(long dateTime,String timeZone, String format){
    String time = null;
    try{
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dateTime);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
        time = sdf.format(cal.getTime());
    }
    catch(Exception e){
        //logger.log(Level.SEVERE,"\n ERROR**********, Exception during get formated time: "+e+"\n");       
    }
    return time;
}

Calendar calendar = Calendar.getInstance();
TimeZone zone = calendar.getTimeZone();
String timeZone = zone.getID();

String msgAtTime =  getFormattedTime(System.currentTimeInMillis(), timezone, "MMM dd, hh:mm a");

msgTextVies.setText(msgAtTime);

我想使用上面的代码显示消息创建时间:

//显示日期时间

DateTime createdAt = message.getCreatedAt();

但是我不知道如何使用以前的代码来实现它。

【问题讨论】:

    标签: java android datetime timestamp


    【解决方案1】:

    您只需使用以下代码即可获取消息创建时间。

    public String getCreatedAt()
    {
        Calendar c1 = Calendar.getInstance();      
        String msg_time= c1.get(Calendar.YEAR) + c1.get(Calendar.MONTH) + c1.get(Calendar.DAY_OF_MONTH) + c1.get(Calendar.HOUR_OF_DAY) + c1.get(Calendar.MINUTE);
        return msg_time;
    }
    

    我没有设置任何具体的格式,但你可以根据你的要求进行调整。

    希望它对你有用。

    【讨论】:

    • c1.get(Calendar.MONTH) 很难提供直观的月份数(索引从零开始)。而且我认为,@Android_learner 首先想要月份作为缩写,其次在代码组织方面存在相当大的问题,因为他自己已经完成了解决方案的所有部分。
    【解决方案2】:

    你可以通过两种方式做到这一点。

    1.通过设备端数据库: 在设备端建立数据库,存储消息信息和获取时间。并将该数据库数据填充到您的应用程序中。因此,您将在时间轴中获得所有发布消息的时间。

    2。通过服务器端数据库:希望您调用 Web 服务将消息从一个用户发送到另一个用户。那时,还要传递您设备的当前时间。或者使系统在获得任何条目时也将具有该表的当前时间戳的条目。因此,每当您调用网络服务时,您都会收到消息发布时间。在列表中填充该时间。

    如果您不清楚,请告诉我。

    【讨论】: