Java中日期API常见问题整理

今天在使用Java日期API的时候遇到的一些问题,,自己整理了下。貌似JDK8中有关于时间行的API,可是JDK8用的还不是很多,先弄明白7的相关知识。 问题1:如何以制定格式显示时间? 问题2:如何计算时间间隔? 问题3:如何计算指定时间间隔以后的时间?

下面直接上代码(使用JUnit4进行测试):

import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import org.junit.Test;{() {Date date = new Date();DateFormat format = new SimpleDateFormat(“yyyy-MM-dd kk:mm:ss”);String time = format.format(date);System.out.println(“北京时间:” + time);}() {Date begin = new Date();for (int i = 0; i < Integer.MAX_VALUE; i++) {}Date end = new Date();long beginTime = begin.getTime();long endTime = end.getTime();System.out.println(“循环历时:” + (endTime – beginTime) + “ms”);}() {DateFormat format = new SimpleDateFormat(“yyyy-MM-dd kk:mm:ss”);Date begin = new Date();int interval = 30;Calendar calendar = Calendar.getInstance();calendar.setTime(begin);calendar.add(Calendar.MINUTE, interval);Date end = calendar.getTime();System.out.println(“现在时间:” + format.format(begin));System.out.println(interval + “分钟后:” + format.format(end));}}

Calendar和Date类有什么不同呢? 在JDK1.1以前,Date类负责时间格式化和时间到年与日转换等功能。JDK1.1以后时间的格式化由DateFormat类负责,时间与年月日等的转换等功能由Calender负责。这就是为什么我们看到Date类中的好多方法都是Depreated的原因。

你在会议中吵架时,尼泊尔的背包客一起端起酒杯坐在火堆旁。

Java中日期API常见问题整理

相关文章:

你感兴趣的文章:

标签云: