android获取当前时间
时间: 2023-10-18 17:18:13 浏览: 42
您可以使用Java中的Date和SimpleDateFormat类来获取当前时间。以下是一个示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class GetCurrentTime {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(new Date());
System.out.println("Current time: " + currentTime);
}
}
```
在上面的示例中,我们创建了一个SimpleDateFormat对象,并将其格式设置为“yyyy-MM-dd HH:mm:ss”,这表示我们要获取当前时间的年月日时分秒。然后,我们使用Date类创建了一个当前时间的实例,并使用SimpleDateFormat的format()方法将其转换为字符串。最后,我们将结果打印出来。
相关问题
android 获取当前时间
在 Android 中,可以使用系统提供的类来获取当前时间。以下是获取当前时间的两种方式:
1. 使用系统时间戳
```
long currentTimeMillis = System.currentTimeMillis();
```
这会返回自 1970 年 1 月 1 日以来的当前时间(以毫秒为单位)。
2. 使用 Calendar 类
```
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
```
这会返回当前年份、月份、日期、小时、分钟和秒数。需要注意的是,Calendar 类中月份是从 0 开始计数的,因此需要加上 1 才是正确的月份。
android 获取当前时间精准到毫秒
你可以使用 `System.currentTimeMillis()` 方法来获取当前时间的毫秒数。这个方法返回的是自1970年1月1日以来经过的毫秒数。以下是一个获取当前时间精确到毫秒的示例代码:
```java
long currentTimeMillis = System.currentTimeMillis();
```
如果你想要将这个毫秒数转换成具体的时间格式,可以使用 `SimpleDateFormat` 类来进行格式化。以下是一个示例代码:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formattedDate = sdf.format(new Date(currentTimeMillis));
```
这个代码会将 `currentTimeMillis` 转换成形如 `2021-09-08 15:30:45.123` 的时间格式。