java 获取当前时间的三种方法
总结java里面关于获取当前时间的一些方法
System.currentTimeMillis()
获取标准时间可以通过System.currentTimeMillis()方法获取,此方法不受时区影响,得到的结果是时间戳格式的。例如:
1543105352845
我们可以将时间戳转化成我们易于理解的格式
SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd'at'HH:mm:ssz"); Datedate=newDate(System.currentTimeMillis()); System.out.println(formatter.format(date));
则该时间戳对应的时间为:
2018-11-25at01:22:12CET
值得注意的是,此方法会根据我们的系统时间返回当前值,因为世界各地的时区是不一样的。
java.util.Date
在Java中,获取当前日期最简单的方法之一就是直接实例化位于Java包java.util的Date类。
Datedate=newDate();//thisobjectcontainsthecurrentdatevalue
上面获取到的日期也可以被format成我们需要的格式,例如:
SimpleDateFormatformatter=newSimpleDateFormat("dd-MM-yyyyHH:mm:ss"); System.out.println(formatter.format(date));
CalendarAPI
Calendar类,专门用于转换特定时刻和日历字段之间的日期和时间。
使用Calendar获取当前日期和时间非常简单:
Calendarcalendar=Calendar.getInstance();//getscurrentinstanceofthecalendar
与date一样,我们也可以非常轻松地format这个日期成我们需要的格式
SimpleDateFormatformatter=newSimpleDateFormat("dd-MM-yyyyHH:mm:ss"); System.out.println(formatter.format(calendar.getTime()));
上面代码打印的结果如下:
25-11-201800:43:39
Date/TimeAPI
Java8提供了一个全新的API,用以替换java.util.Date和java.util.Calendar。Date/TimeAPI提供了多个类,帮助我们来完成工作,包括:
- LocalDate
- LocalTime
- LocalDateTime
- ZonedDateTime
- LocalDate
LocalDate只是一个日期,没有时间。这意味着我们只能获得当前日期,但没有一天的具体时间。
LocalDatedate=LocalDate.now();//getsthecurrentdate
我们可以format它
DateTimeFormatterformatter=DateTimeFormatter.ofPattern("dd-MM-yyyy"); System.out.println(date.format(formatter));
得到的结果只有年月日,例如:
25-11-2018
LocalTime
LocalTime与LocalDate相反,它只代表一个时间,没有日期。这意味着我们只能获得当天的当前时间,而不是实际日期:
LocalTimetime=LocalTime.now();//getsthecurrenttime
可以按如下方式format
DateTimeFormatterformatter=DateTimeFormatter.ofPattern("HH:mm:ss"); System.out.println(time.format(formatter));
得到的结果类似如下:
00:55:58
LocalDateTime
最后一个是LocalDateTime,也是Java中最常用的Date/Time类,代表前两个累的组合-即日期和时间的值:
LocalDateTimedateTime=LocalDateTime.now();//getsthecurrentdateandtime
format的方式也一样
DateTimeFormatterformatter=DateTimeFormatter.ofPattern("dd-MM-yyyyHH:mm:ss"); System.out.println(dateTime.format(formatter));
得到的日期结果类似于:
25-11-201800:57:20
总结
以上所述是小编给大家介绍的java获取当前时间的三种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!