How to get current timestamp in Android without it updating like a clock

南笙酒味 提交于 2019-12-24 13:17:57

问题


I'm trying to get a timestamp in android, this is my code;

public String getTimestamp() {
    String timestamp = DateFormat.getDateTimeInstance().format(new Date());
    return timestamp;
}

When I create a variable to display the timestamp.

Ex) String timestamp = getTimestamp();

This should save the current timestamp as a string. However when I print this string 'timestamp', it continues updating in real time like a clock. I just want the current timestamp. I don't have it in a for loop or anything, where it could be updating.

Here is where it's being printed out:

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rootView = inflater.inflate(R.layout.single_list_item, parent, false);
    TextView nameView = (TextView) rootView.findViewById(R.id.idView);

    GeLoBeacon beacon = beacons.get(position);

    if (!beaconsFound.contains(Integer.toString(beacon.getBeaconId()))) {
        beaconsFound.add(Integer.toString(beacon.getBeaconId()));
    }
    String times = getTimestamp();
    nameView.setText(times);
    return rootView;
}

回答1:


Here you go:

public String getTimestamp() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
      return sdf.format(new Date());
}

Change the format("yyyy-MM-dd'T'HH:mm:ss") and get your date in that particular format!




回答2:


Your method getView() called on each item of adapter and therefore different time set on each item. Set timestamp as field variable in adapter before calling method listView.setAdapter()




回答3:


define timeStamp as a field variable then use setTimeStamp(){ //to assign current time} and getimeStamp() { return timeStamp;) to read the timeStamp value.



来源:https://stackoverflow.com/questions/31168695/how-to-get-current-timestamp-in-android-without-it-updating-like-a-clock

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