下面是我的云 Firestore 的数据库。该 DatePosted 显示 2019 年 12 月 2 日晚上 8 点 19 分 UTC +8。根据我使用的代码并运行我的应用程序,它显示了一个不可读的数字。我如何从云 Firebase 检索数据是否正确?如果错误,我如何检索该时间戳并使其可读?
论坛适配器.java
public class ForumAdapter extends FirestoreRecyclerAdapter<Forum,ForumAdapter.ForumHolder> {
private OnItemClickListener listener;
public ForumAdapter(FirestoreRecyclerOptions<Forum> options) {
super(options);
}
@Override
public void onBindViewHolder(ForumHolder forumHolder, int i, Forum forum) {
forumHolder.textViewTitle.setText(forum.getTitle());
forumHolder.textViewDescription.setText(forum.getDescription());
forumHolder.timeStamp.setText(forum.getDatePosted().toString());
}
@NonNull
@Override
public ForumHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforumtitle,parent,false);
return new ForumHolder(v);
}
class ForumHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDescription;
TextView timeStamp;
public ForumHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.tvTitle);
textViewDescription = itemView.findViewById(R.id.tvDescription);
timeStamp = itemView.findViewById(R.id.tvTimestamp);
textViewTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
// NO_POSITION to prevent app crash when click -1 index
if(position != RecyclerView.NO_POSITION && listener !=null ){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
@Override
public int getItemCount() {
return super.getItemCount();
}
}
论坛.java
public class Forum {
private String Title;
private String Description;
private String User;
private com.google.firebase.Timestamp DatePosted;
public Forum() {
}
public Forum(String title, String description, Timestamp datePosted,String user) {
Title = title;
Description = description;
DatePosted = datePosted;
User = user;
}
public String getUser() {
return User;
}
public void setUser(String user) {
User = user;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Timestamp getDatePosted() {
return DatePosted;
}
public void setDatePosted(Timestamp datePosted) {
DatePosted = datePosted;
}
}
最佳答案
当您查询带有时间戳字段的文档时,您将得到 Timestamp对象回来。如果您更喜欢 Date 对象,可以使用它的 toDate方法。
您需要编写一些代码来格式化它以供显示。对于移动和 Web 应用程序来说,这是一项非常常见的任务。
关于android - 如何从 Cloud Firestore 制作可读的时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59179551/