我希望使用ServerValue.Timestamp以长格式iam的时间戳值

时间:2017-07-20 00:51:25

标签: java android firebase firebase-realtime-database

我使用ServerValue.TimeStamp并使用hashmap上传到firebase HashMap<String, Object> map = new HashMap(); map.put("timestamp", ServerValue.TIMESTAMP);

但我需要长时间获取TimeStamp的值而不将其上传到firebase 我试图把它转换为long但总是收到ClassCastException

        Map<String, Object> currentTime = new HashMap<>();
    currentTime.put("timestamp", ServerValue.TIMESTAMP);
    return (long) currentTime.get("timestamp");  

任何帮助?!

2 个答案:

答案 0 :(得分:2)

当我通过替换

进行模型类的小改动时,它对我有用
Map<String , String> timestamp;

Object timestamp;

因为Object类是java中所有类的父类所以任何子类都可以正常工作,就像在firebase中保存值一样好,当你需要检索值时,只需要将此对象转换为很长

这是我使用的模型

public class UserModel {
private String name , phone, email, birthDate, userType, address;
Object timestamp;

// for firebase retrieving data
public UserModel() {
}

public UserModel(String name, String phone, String email, String birthDate, String userType, String address) {
    this.name = name;
    this.phone = phone;
    this.email = email;
    this.birthDate = birthDate;
    this.userType = userType;
    this.address = address;
    //get Date from firebase server automatic
    this.timestamp =  ServerValue.TIMESTAMP;
}

public String getName() {
    return name;
}

public String getPhone() {
    return phone;
}

public String getEmail() {
    return email;
}

public String getBirthDate() {
    return birthDate;
}

public String getUserType() {
    return userType;
}

public String getAddress() {
    return address;
}

@Override
public String toString() {
     String data = " user name" + this.name+" , user Address : "
             +this.address+" , user phone "+this.phone+" , user email : "+this.email
             +" , user birthdate : "+this.birthDate+" , user type : "+this.userType
             + " , registered time "+this.timestamp;
    return data;
}

/* public String getLoginDate() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'");
    Date date = new Date(si)
    return ;
}*/
}
  

我将它上传到firebase successufly

firebase image

  

以下是从firebase下载数据时收到的reslt

data after download from firebase

答案 1 :(得分:0)

我有同样的问题,我解决了。这将帮助你:D

    String key = mDatabase.push().getKey();mDatabase.child(ke).setValue(mMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        mDatabase.push().child("date").setValue(ServerValue.TIMESTAMP);
                                    }
                                });
mDatabase.child(ke).child("date").setValue(ServerValue.TIMESTAMP);