Android Date如何获取格式化时间
时间: 2024-03-27 09:40:27 浏览: 11
要获取格式化时间,可以使用 SimpleDateFormat 类。以下是一个获取当前时间并格式化的示例代码:
```java
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String formattedDate = dateFormat.format(date);
Log.d("Formatted Date", formattedDate);
```
在上面的代码中,我们定义了一个 SimpleDateFormat 类型的 dateFormat 变量,它使用 "yyyy-MM-dd HH:mm:ss" 格式字符串来指定日期格式。然后我们使用 Date 类创建了一个当前时间的实例,并将其格式化为指定格式的字符串。最后,我们将格式化后的时间字符串打印到日志中。
你可以根据需要调整 SimpleDateFormat 类中的格式字符串来获取不同格式的日期和时间。
相关问题
android 时间格式化
在 Android 中,可以使用 SimpleDateFormat 类来格式化时间。下面是一个例子:
```java
Date date = new Date(); // 获取当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义时间格式
String formattedTime = sdf.format(date); // 格式化时间
```
在上面的例子中,格式化后的时间字符串将会是类似于 "2021-10-12 15:30:00" 这样的格式。你可以根据自己的需求来定义时间格式。更多关于 SimpleDateFormat 的用法可以参考官方文档:https://developer.android.com/reference/java/text/SimpleDateFormat
android时间格式化
在 Android 中,可以使用 `java.text.DateFormat` 类来格式化时间。 例如,要将当前时间格式化为中国的默认格式(类似于 "2022年12月29日 星期四 下午3点45分56秒"),可以使用以下代码:
```
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.CHINA);
String date = df.format(new Date());
```
如果要自定义格式,可以使用 `java.text.SimpleDateFormat` 类。 例如,要将时间格式化为 "2022/12/29 15:45:56" 的格式,可以使用以下代码:
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String date = sdf.format(new Date());
```
请注意,上述代码均假设使用的是系统默认时区。 如果需要使用特定时区,可以在创建 `DateFormat` 或 `SimpleDateFormat` 对象时传入相应的 `TimeZone` 参数。
希望这能帮到您!