Java 时间类 Date 和 Calendar

在项目中获取一个yyyy-MM-dd HH:mm:ss格式的时间字符串

 1 package org.htsg.kits;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Calendar;
 5 import java.util.Date;
 6 
 7 /**
 8  * @author Microsoft
 9  */
10 public class DateKit {
11     /**
12      * 获取当前时间,格式为yyyy-MM-dd HH:mm:ss
13      *
14      * @return String
15      */
16     public static String now() {
17         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
18         Calendar calendar = Calendar.getInstance();
19         Date date = calendar.getTime();
20         return simpleDateFormat.format(date);
21     }
22 
23     /**
24      * 获取当前时间,格式为yyyy-MM-dd HH:mm:ss
25      *
26      * @return String
27      */
28     public static String quickNow() {
29         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
30         Date date = new Date();
31         return simpleDateFormat.format(date);
32     }
33 }

时间上的横向对比:

 1 package org.htsg.test;
 2 
 3 import org.htsg.kits.DateKit;
 4 import org.junit.Test;
 5 
 6 /**
 7  * @author Microsoft
 8  */
 9 public class MainTest {
10 
11     @Test
12     public void testDateKit01() {
13         for (int i = 0; i < 10; i++) {
14             DateKit.now();
15         }
16     }
17 
18     @Test
19     public void testDateKit02() {
20         for (int i = 0; i < 10; i++) {
21             DateKit.quickNow();
22         }
23     }
24 }

测试结果:

Java 时间类 Date 和 Calendar_第1张图片

增加循环次数到1000:

Java 时间类 Date 和 Calendar_第2张图片

增加循环次数到10000000:

Java 时间类 Date 和 Calendar_第3张图片

综合来说使用在使用上述方法获取一个yyyy-MM-dd HH:mm:ss格式的时间字符串时,new Date() 比 Calendar.getInstance()速度上要快些。

修改方法为:

1 public static String now() {
2         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3         Calendar calendar = Calendar.getInstance();
4         return simpleDateFormat.format(calendar.getTime());
5     }

循环测试1000次:

速度上并没有明显的提升。

你可能感兴趣的:(Java 时间类 Date 和 Calendar)