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 }

测试结果:

增加循环次数到1000:

增加循环次数到10000000:

综合来说使用在使用上述方法获取一个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次:

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

转载于:https://www.cnblogs.com/htsg/p/10814957.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值