引导语:日期和时间类编程题也是Java笔试中会出现的题目,以下是本站小编分享给大家的Java面试试题日期和时间,欢迎参考学习!
日期和时间:
- 如何取得年月日、小时分钟秒?
- 如何取得从1970年1月1日0时0分0秒到现在的毫秒数?
- 如何取得某月的最后一天?
- 如何格式化日期?
答:
问题1:创建ndar 实例,调用其get()方法传入不同的参数即可获得参数所对应的值。Java 8中可以使用lDateTimel来获取,代码如下所示。
1234567891011121314151617181920 | public class DateTimeTest {
public static void main(String[] args) {
Calendar cal = nstance();
tln(());
tln((H)); // 0 - 11
tln(());
tln((_OF_DAY));
tln((TE));
tln((ND));
// Java 8
LocalDateTime dt = ();
tln(ear());
tln(onthValue()); // 1 - 12
tln(ayOfMonth());
tln(our());
tln(inute());
tln(econd());
} } |
问题2:以下方法均可获得该毫秒数。
123 | nstance()imeInMillis(); entTimeMillis(); emDefaultZone()is(); // Java 8 |
问题3:代码如下所示。
12 | Calendar time = nstance(); ctualMaximum(_OF_MONTH); |
问题4:利用Format 的`子类(如SimpleDateFormat类)中的format(Date)方法可将日期格式化。Java 8中可以用TimeFormatter来格式化时间日期,代码如下所示。
123456789101112131415161718 | import leDateFormat; import lDate; import TimeFormatter; import ; class DateFormatTest {
public static void main(String[] args) {
SimpleDateFormat oldFormatter = new SimpleDateFormat( "yyyy/MM/dd" );
Date date1 = new Date();
tln(at(date1));
// Java 8
DateTimeFormatter newFormatter = ttern( "yyyy/MM/dd" );
LocalDate date2 = ();
tln(at(newFormatter));
} } |
补充:Java的时间日期API一直以来都是被诟病的东西,为了解决这一问题,Java 8中引入了新的时间日期API,其中包括LocalDate、LocalTime、LocalDateTime、Clock、Instant等类,这些的类的设计都使用了不变模式,因此是线程安全的设计。