android 实时获取系统时间
时间: 2023-07-28 07:36:02 浏览: 46
获取 Android 系统时间可以使用 Java 中的 `java.util.Date` 和 `java.text.SimpleDateFormat` 类。
以下是一个获取当前系统时间并格式化为字符串的示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取当前时间
Date date = new Date();
// 设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 格式化时间为字符串
String currentTime = sdf.format(date);
// 将时间显示到 TextView 上
TextView textView = findViewById(R.id.textView);
textView.setText("当前时间为:" + currentTime);
}
}
```
在上述代码中,我们首先使用 `new Date()` 获取当前时间,然后使用 `SimpleDateFormat` 设置时间格式,并将时间格式化为字符串。最后,我们将时间字符串显示到 TextView 上。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)