如何使用线程安全的时间类(jdk1.8) |
您所在的位置:网站首页 › java线程安全类型 › 如何使用线程安全的时间类(jdk1.8) |
1. Java8新时间特性
我们一般描述时间会用Date()对象来表示,但是为了时间显示更加符合习惯,会使用SimpleDateFormat来进行格式化。但是这种使用是存在缺陷的。 1.1 SimpleDateFormat线程不安全SimpleDateFormat是线程不安全的,因为这个这个类是继承于DateFormat的,DateFormat中有一个Calender属性,可以说SimpleDateFormat的格式化就是依赖于这个属性进行操作的。 SimpleDateFormat的format方法中将传入的Date对象会交给calendar属性(calendar.setTime(date););当A线程传入时间a调用format方法进行格式化,format方法还没执行完,此时B线程传入时间b调用format方法进行格式化,则A线程中的calendar的time就变成了B线程传入的时间b了,当执行format方法中的subFormat方法时,获取到的格式化的时间是不正确的。 Java8中可以使用LocalDate(描述日期,即年月日)、LocalTime(描述时间,即时分秒)、LocalDateTime(日期时间,即年月日时分秒)对象来处理日期时间。 1.2 LocalDate的基本使用 public class Test2 { public static void main(String[] args){ // 获取当前日期 LocalDate date = LocalDate.now(); System.out.println(date); // 获取年月日 int year = date.getYear(); int month = date.getMonthValue(); // date.getMonth()获取到的是Month对象 int day = date.getDayOfMonth(); System.out.println(year+"-"+month+"-"+day); // 修改日期 LocalDate newDate = date.withYear(2019).withMonth(12).withDayOfMonth(12); System.out.println("修改后的时间:"+newDate); // 解析日期 LocalDate parseDate = LocalDate.parse("2008-08-08"); System.out.println("解析日期:"+parseDate); } }结果: 结果: 注意: 解析日期要注意,日期格式必须为HH:mm:ss这种,比如“20:2:12”这种是会抛出异常的,必须要是两位的时分秒。而且间隔必须是“:”不能是“-”,和LocalDate是不同的。 1.4 LocalDateTime的基本使用 public class Test2 { public static void main(String[] args){ // LocalDateTime的使用 LocalDateTime date = LocalDateTime.now(); System.out.println(date); // 获取年月日,时分秒 // 和上面的LocalDate和LocalTime一样。 System.out.println(date.getYear()+"-"+date.getMonthValue()+"-"+date.getDayOfMonth()+" "+ date.getHour()+":"+date.getMinute()+":"+date.getSecond()); // 修改日期时间 System.out.println(date.withYear(2009).withHour(22).withSecond(12)); // 解析日期时间 System.out.println(LocalDateTime.parse("2008-12-02T12:12:12")); } }结果: |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |