You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为帖子添加时间戳?Firebase代码实现疑问咨询

给Firebase帖子添加发布时间戳的解决方案

嘿,我来帮你搞定这个时间戳的问题!你已经通过DateFormat.getDateTimeInstance().format(new Date())拿到了当前时间的字符串,接下来只需要把它和消息内容一起存入Firebase数据库,就能让帖子附带发布时间了。具体步骤如下:

  • 打包帖子数据:在SendButtonClicked方法里,拿到输入的消息内容后,把时间戳和消息一起放到一个Map里(也可以用自定义实体类,Map更灵活):

    public void SendButtonClicked(View view){
        FirebaseUser mCurrentUser = mAuth.getCurrentUser();
        DatabaseReference mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
        final String messageValue = editMessage.getText().toString().trim();
        
        // 新增代码:打包消息和时间戳
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        Map<String, Object> postData = new HashMap<>();
        postData.put("message", messageValue);
        postData.put("publishTime", currentDateTimeString); // 存储格式化后的时间字符串
        postData.put("userId", mCurrentUser.getUid()); // 可选:加上发布者ID,方便后续关联用户信息
    
  • 存储到Firebase数据库:接下来把打包好的数据存到帖子对应的节点下,记得用push()生成唯一的帖子ID,避免数据覆盖:

    // 继续完成方法逻辑
        DatabaseReference mPostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
        String postId = mPostsRef.push().getKey(); // 生成唯一的帖子ID
        
        // 把数据存入数据库
        mPostsRef.child(postId).setValue(postData)
                .addOnSuccessListener(v -> {
                    // 发布成功后清空输入框,给用户反馈
                    editMessage.setText("");
                    Toast.makeText(getApplicationContext(), "发布成功!", Toast.LENGTH_SHORT).show();
                })
                .addOnFailureListener(e -> {
                    // 处理发布失败的情况
                    Toast.makeText(getApplicationContext(), "发布失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
    }
    
  • 进阶优化建议:如果后续需要按发布时间排序帖子,用数值型时间戳会比字符串更方便。你可以把获取时间的代码改成这样:

    long currentTimestamp = new Date().getTime(); // 获取自1970年以来的毫秒数,是long类型
    

    然后把postData.put("publishTime", currentDateTimeString)改成postData.put("timestamp", currentTimestamp)。之后查询帖子时,就能用mPostsRef.orderByChild("timestamp").limitToLast(20)轻松获取最新的20条帖子,排序效率和准确性都更高!

内容的提问来源于stack exchange,提问作者Joshua Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:40:56