System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

System.currentTimeMillis() is obviously the most efficient since it does not even create an object, but new Date() is really just a thin wrapper about a long, so it is not far behind. Calendar, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and all the oddities that are inherent to dates and times (leap years, daylight savings, timezones, etc.).

System.currentTimeMillis的()显然是最有效的,因为它甚至不创建一个对象,

Date()仅仅是一个大约长的瘦包装器,所以它也不甘落后。

日历,是相对缓慢和非常复杂的,因为它有处理相当复杂和奇特,是固有的日期和时间(闰年,夏令时,时区等)

package day02; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Calendar; import java.util.Date; public class DateDemo { public static void main(String[] args) throws ParseException { System.out.println(System.currentTimeMillis()); Date date = new Date(); System.out.println(date.getTime()); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strDate = df.format(date); System.out.println("这是日期转字符串之后的格式:" + strDate); String str = "2025-09-05 08:09:20"; Date date1 = df.parse(str); System.out.println("这是字符串转日期之后的格式:" + date1); Calendar calendar = Calendar.getInstance(); System.out.println("这是CalendargetTime()方法:" + calendar.getTime()); System.out.println("获取年份:" + calendar.get(Calendar.YEAR)); System.out.println("获取月份:" + calendar.get(Calendar.MONTH)); LocalDate localDate = LocalDate.now(); System.out.println("localDate:" + localDate); LocalTime localTime = LocalTime.now(); System.out.println("localTime:" + localTime); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("localDateTime:" + localDateTime); // 获取当前星期几 int week = calendar.get(Calendar.DAY_OF_WEEK) - 1; String weekDate = ""; switch (week) { case 0: weekDate = "星期日"; break; case 1: weekDate = "星期一"; break; case 2: weekDate = "星期二"; break; case 3: weekDate = "星期三"; break; case 4: weekDate = "星期四"; break; case 5: weekDate = "星期五"; break; case 6: weekDate = "星期六"; break; } System.out.println("今天是 " + weekDate); } } 分析一下这段代码
09-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值