2015-07-01 27 views
1

我试图在android中获取时间戳,这是我的代码;如何在Android中获取当前时间戳,而不需要像更新时钟那样更新

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

当我创建一个变量来显示时间戳。例如:

Ex)String timestamp = getTimestamp();

这应该将当前时间戳保存为一个字符串。但是,当我打印这个字符串'时间戳'时,它会像时钟一样实时更新。我只想要当前的时间戳。我没有在for循环或任何东西,它可以更新。

这里是它被打印出来:

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

如果您调用了getTimestamp()一次,返回String不能更新,请显示代码打印此字符串的位置 – Max77

+0

@ Max77我在代码中添加了代码正在打印出来。 – Programmer

回答

0

在这里你去:

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

更改格式( “YYYY-MM-dd'T'HH:MM:SS”)并以特定的格式获取你的日期!

+0

这只是格式化时间戳的一种不同方式,它不能解决更新时间戳的问题。 – blalasaadri

0

将timeStamp定义为字段变量,然后使用setTimeStamp(){//指定当前时间}和getimeStamp(){return timeStamp;)来读取timeStamp值。

1

您的方法getView()在每个适配器上调用,因此在每个项目上设置不同的时间。在调用方法之前在适配器中设置时间戳作为字段变量listView.setAdapter()