Java获取当前时间
目录
- 1、Java.util.Date
- 2、System.currentTimeMillis()
- 3、Calendar类
1、Java.util.Date
Date date = new Date();
通过Date类来获取当前时间,比较常用。需要使用Java.util.Date类,速度一般。
2、System.currentTimeMillis()
通过System类中的currentTimeMillis方法来获取当前时间,无需导入类,速度最快。
此方法优势是不受时区的影响,但是得到结果是时间戳的格式
System.currentTimeMillis();
//结果为 153452345528345 格式
可以通过代码将时间戳转化为我们可以理解的格式:
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));
转换后格式如下:
2023-05-13 at 11:34:12 CET
3、Calendar类
Calendar 类专门用来转换特定时刻和日历字段之间的日期和时间
Calendar calendar = Calendar.getInstance();
同时它还支持更自由的取时间
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
非常灵活
还没有评论,来说两句吧...