How to show Firestore serverTimestamp correctly depending on local

北慕城南 提交于 2019-12-11 14:20:57

问题


I cant get this right and wonder how to show the Firestore FieldValue.serverTimestamp() formatet individual depending on what local the device has.

The Firestore timestamp look like this

Sat Mar 10 19:42:32 GMT+01:00 2018

try {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS", Locale.getDefault());
        Date parsedDate = dateFormat.parse("Sat Mar 10 19:42:32 GMT+01:00 2018");
        txtCreationDate.setText(new Date(parsedDate.getTime()).toString());
     } catch (ParseException e) {
        txtCreationDate.setText("time error");
     }

If one user i USA create the date time object then if another user i Italy view it then the creation time must adjusted to his clock

I have read many pages about this but the dateFormat parser give me error only.
Please advice


回答1:


Assuming that you have a model class named MyClass that has a Date field and public setters and getters, to get the date, please use the following code:

Date date = yourClass.getDate();
if (date != null) {
    DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.getDefault());
    String creationDate = dateFormat.format(date);
    Log.d("TAG", creationDate);
}



回答2:


What I normally do is simply use Date and setTimezine. The timestamp variable in my models are long variables and I use a code like this to convert the server time into a local one.

    DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    formatter.setTimeZone(TimeZone.getTimeZone("STRING FOR TIMEZONE"));
    String localizedToday = formatter.format(YOURDATEOBJECT);


来源:https://stackoverflow.com/questions/49221968/how-to-show-firestore-servertimestamp-correctly-depending-on-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!