简体   繁体   中英

How to save date and time in an orderly format Firebase & Android Studio

I am creating a social app and I want to save the date and time of a post when someone uploads it. I want it to be saved for example as dd-MM-yyyy HH:mm:ss . Currently this is how it looks

当前日期和时间戳

So this is the code that I have in a method.

public static String getTimeDate(long timestamp){
    try{
        Date netDate = (new Date(timestamp));
        SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
        return sfd.format(netDate);
    } catch(Exception e) {
        return "date";
    }
}

I expect it to save the date and time that the post was uploaded in the format I want. But my problem is uploading it correctly in the Firebase DB. This is how I am uploading my current fields.

HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("postid", postid);
hashMap.put("postimage", myUrl);
hashMap.put("description", description.getText().toString());
hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());

I am trying to upload the timestamp like:

hashMap.put("date_time", getTimeDate() );

But when I hover over the parenthesis next to getTimeDate() it says Expected 1 arguments but found 0 so I'm guessing I have to use a string instead of the method name. Can someone help me on what to do?

To get current time when someone upload the data, you can from new Date() and change your method without having a parameter argument

public static String getTimeDate() { // without parameter argument
    try{
        Date netDate = new Date(); // current time from here
        SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
        return sfd.format(netDate);
    } catch(Exception e) {
        return "date";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM