问题
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