网站首页 > 编程文章 正文
Date:Old version
SimpleDateFormat线程安全问题
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
ExecutorService pool = Executors.newFixedThreadPool(10);
Callable<Date> callable = new Callable<Date>() {
@Override
public Date call() throws Exception {
//synchronized同步代码块解决线程不安全的问题,java.lang.NumberFormatException是因线程不安全造成的
synchronized (sdf){
return sdf.parse("20200215");
}
}
};
List<Future<Date>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<Date> task = pool.submit(callable);
list.add(task);
}
for (Future<Date> future : list) {
System.out.println(future.get());
}
pool.shutdown();
}
}
class Test1{
public static void main(String[] args) throws Exception{
//JDK1.8新特性,避免了线程不安全的问题
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
ExecutorService pool = Executors.newFixedThreadPool(10);
Callable<LocalDate> callable = new Callable<LocalDate>() {
@Override
public LocalDate call() throws Exception {
return LocalDate.parse("20200215",dtf);
}
};
List<Future<LocalDate>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<LocalDate> task = pool.submit(callable);
list.add(task);
}
for (Future<LocalDate> future : list) {
System.out.println(future.get());
}
pool.shutdown();
}
}
Date API
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Set;
public class Test {
public static void main(String[] args) throws Exception{
//创建本地时间
//方式一:
LocalDateTime localDateTime = LocalDateTime.now();
//方式二:
// LocalDateTime localDateTime1 = LocalDateTime.of(2020,04,05,12,34);
System.out.println(localDateTime);
System.out.println(localDateTime.getYear());
System.out.println(localDateTime.getMonthValue());
System.out.println(localDateTime.getDayOfMonth());
//添加两天
LocalDateTime localDateTime1 = localDateTime.plusDays(2);
System.out.println(localDateTime1);
//减少一个月
LocalDateTime localDateTime2 = localDateTime.minusMonths(1);
System.out.println(localDateTime2);
//Instant 时间戳
Instant instant = Instant.now();
System.out.println(instant.toString());
System.out.println(instant.toEpochMilli());//毫秒
System.out.println(System.currentTimeMillis());
//添加减少时间
Instant instant1 = instant.plusSeconds(10);
System.out.println(Duration.between(instant,instant1).toMillis());//打印时间差
//ZoneId 时区
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
for (String availableZoneId : availableZoneIds) {
System.out.println(availableZoneId);
}
System.out.println(ZoneId.systemDefault().toString());//打印当前时区
//Date--->Instant--->LocalDateTime的转换
Date date = new Date();
Instant instant2 = date.toInstant();
System.out.println(instant2);
LocalDateTime localDateTime3 = LocalDateTime.ofInstant(instant2,ZoneId.systemDefault());
System.out.println(localDateTime3);
System.out.println("------------------------------");
//LocalDateTime--->Instant--->Date的转换
Instant instant3 = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println(instant3);
Date from = Date.from(instant3);
System.out.println(from);
//DateTimeFormatter:格式化类,线程安全的类
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//把时间格式化字符串
String format = dtf.format(LocalDateTime.now());
System.out.println(format);
//把字符串解析成时间
LocalDateTime localDateTime4 = LocalDateTime.parse("2020-03-10 10:34:23",dtf);
System.out.println(localDateTime4);
}
}
LocalDate ---- 日期的操作
package com.demo;
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
public class JDK8Date {
@Test
public void test01() {
// 创建指定日期
LocalDate date01 = LocalDate.of(2021, 05, 06);
// 获取当前日期
LocalDate date02 = LocalDate.now();
// 根据LocalDate对象获取对应的日期信息
// 获取年
int year = date02.getYear();
// 获取月
Month month = date02.getMonth();
// 获取日
int dayOfMonth = date02.getDayOfMonth();
// 获取星期
DayOfWeek dayOfWeek = date02.getDayOfWeek();
}
}
LocalTime ---- 时间的操作
package com.demo;
import org.junit.Test;
import java.time.LocalTime;
public class JDK8Date {
@Test
public void test01() {
// 获取指定的时间
LocalTime time01 = LocalTime.of(5, 26, 33, 324242);
// 获取当前时间
LocalTime time02 = LocalTime.now();
// 获取时间信息
// 时
int hour = time02.getHour();
// 分
int minute = time02.getMinute();
// 秒
int second = time02.getSecond();
// 纳秒
int nano = time02.getNano();
}
}
LocalDateTime ---- 日期时间操作
package com.demo;
import org.junit.Test;
import java.time.LocalDateTime;
public class JDK8Date {
@Test
public void test01() {
// 获取指定的日期时间
LocalDateTime dateTime = LocalDateTime.of(2023, 06, 01, 12, 12, 33, 232424);
// 获取当前日期时间
LocalDateTime now = LocalDateTime.now();
// 获取日期时间信息
// 年
int year = now.getYear();
// 月
int month = now.getMonth().getValue();
// 日
int dayOfMonth = now.getDayOfMonth();
// 星期
int dayOfWeek = now.getDayOfWeek().getValue();
// 时
int hour = now.getHour();
// 分
int minute = now.getMinute();
// 秒
int second = now.getSecond();
// 纳秒
int nano = now.getNano();
}
}
日期时间的修改和比较
- 日期时间的修改
修改日期时间,重新创建日期时间对象,对原有的日期时间对象不会修改,不会有线程安全问题
package com.demo;
import org.junit.Test;
import java.time.LocalDateTime;
public class JDK8Date {
@Test
public void test01() {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 修改年
LocalDateTime dateTime1 = now.withYear(1998);
// 修改月
LocalDateTime dateTime2 = now.withMonth(10);
// 修改日
LocalDateTime dateTime3 = now.withDayOfMonth(6);
// 修改分
LocalDateTime dateTime4 = now.withMinute(12);
// 加法
// 两天后的日期时间
LocalDateTime dateTime5 = now.plusDays(2);
// 10年后
LocalDateTime dateTime6 = now.plusYears(10);
// 减法
// 10年前的日期时间
LocalDateTime dateTime7 = now.minusYears(10);
// 一周前的日期时间
LocalDateTime dateTime8 = now.minusWeeks(7);
}
}
- 日期时间的比较
package com.demo;
import org.junit.Test;
import java.time.LocalDate;
public class JDK8Date {
@Test
public void test01() {
// 获取当前日期
LocalDate now = LocalDate.now();
// 指定日期
LocalDate date = LocalDate.of(2023, 1, 6);
// now在date之后
boolean after = now.isAfter(date);
// now在date之前
boolean before = now.isBefore(date);
// now与date是否相等
boolean equal = now.isEqual(date);
}
}
- 格式化和解析操作
package com.demo;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class JDK8Date {
@Test
public void test01() {
LocalDateTime now = LocalDateTime.now();
// 默认格式
DateTimeFormatter isoLocalDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
// 将日期时间转换为字符串
String defaultFormat = now.format(isoLocalDateTime);
// 指定格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = now.format(dateTimeFormatter);
// 将字符串解析为一个日期时间类型
LocalDateTime parse = LocalDateTime.parse("1970-05-06 00:00:00", dateTimeFormatter);
}
}
Instance类
package com.demo;
import org.junit.Test;
import java.time.Instant;
public class JDK8Date {
@Test
public void test01() {
// 用于时间的统计
Instant now = Instant.now();
System.out.println("now = " + now);
// 获取纳秒
int nano = now.getNano();
}
}
日期时间差
- Duration: 计算两个时间差(LocalTime)
package com.demo;
import org.junit.Test;
import java.time.Duration;
import java.time.LocalTime;
public class JDK8Date {
@Test
public void test01() {
// 计算时间差
LocalTime now = LocalTime.now();
LocalTime time = LocalTime.of(22, 48, 59);
// 通过Duration计算时间差
Duration duration = Duration.between(now, time);
// 天数的差值
long days = duration.toDays();
// 小时的差值
long hours = duration.toHours();
// 分钟的差值
long minutes = duration.toMinutes();
}
}
- Period: 计算两个日期差(LocalDate)
package com.demo;
import org.junit.Test;
import java.time.LocalDate;
import java.time.Period;
public class JDK8Date {
@Test
public void test01() {
// 计算日期差
LocalDate now = LocalDate.now();
LocalDate date = LocalDate.of(1997, 12, 5);
Period period = Period.between(date, now);
// 年差值
int years = period.getYears();
// 月差值
int months = period.getMonths();
// 天差值
int days = period.getDays();
}
}
TemporalAdjuster ---- 时间矫正器
TemporalAdjusters: 通过该类静态方法提供了大量的常用TemporalAdjuster的实现,简化处理的操作。
package com.demo;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class JDK8Date {
@Test
public void test01() {
// 时间矫正器
LocalDateTime now = LocalDateTime.now();
// 将当前的日期调整到下个月的一号
TemporalAdjuster adJuster = (temporal) -> {
LocalDateTime dateTime = (LocalDateTime) temporal;
LocalDateTime nextMonth = dateTime.plusMonths(1).withDayOfMonth(1);
return nextMonth;
};
LocalDateTime nextMonth = now.with(adJuster);
System.out.println("nextMonth = " + nextMonth); // nextMonth = 2023-05-01T20:51:47.305064600
// 下个月第一天可以使用TemporalAdjusters直接实现
LocalDateTime nextMonth02 = now.with(TemporalAdjusters.firstDayOfNextMonth());
System.out.println("nextMonth02 = " + nextMonth02); // nextMonth02 = 2023-05-01T20:51:47.305064600
}
}
时区
带时区的日期时间类分别为:ZonedDate、ZonedTime、ZonedDateTime
package com.demo;
import org.junit.Test;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class JDK8Date {
@Test
public void test01() {
// 获取所有的时区id
// ZoneId.getAvailableZoneIds().forEach(System.out::println);
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now); // now = 2023-04-22T21:05:40.794340
// 获取标准时间
ZonedDateTime bz = ZonedDateTime.now(Clock.systemUTC());
System.out.println("bz = " + bz); // bz = 2023-04-22T13:05:40.798332900Z
// 使用计算机默认的时区,创建日期时间
ZonedDateTime now1 = ZonedDateTime.now();
System.out.println("now1 = " + now1); // now1 = 2023-04-22T21:05:40.798332900+08:00[Asia/Shanghai]
// 使用指定的时区创建日期时间
ZonedDateTime now2 = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
System.out.println("now2 = " + now2); // now2 = 2023-04-22T06:05:40.800840400-07:00[America/Los_Angeles]
}
}
猜你喜欢
- 2024-09-09 Java JDK11 在Linux上的安装和配置
- 2024-09-09 一份详细介绍JVM的资料(对比JDK8和JDK7)
- 2024-09-09 应用服务器安装指南(应用服务器安装指南下载)
- 2024-09-09 [信创]SpringBoot3 JDK17 整合 MyBatis + 达梦DM8(一)
- 2024-09-09 浅谈 Java线程状态转换及控制(java线程状态转换图)
- 2024-09-09 jdk 1.8 stream基本用法(jdk8 stream map)
- 2024-09-09 jdk安装、配置文档(jdk安装配置教程)
- 2024-09-09 2021年官网下载各个版本JDK最全版与官网查阅方法
- 2024-09-09 11.2.JDK5~JDK8各个版本新特性(jdk8u5)
- 2024-09-09 jdk1.8就带有的Lambda表达式,现在1.9都发布了你不会还没用过吧
你 发表评论:
欢迎- 最近发表
-
- 数据不丢失 从Windows 11的DEV版降级到正式版
- Win11学院:在Windows11 25905预览版中如何启用Dev Drive
- DEVC++的卸载(devcon卸载驱动)
- win11 dev 开发版 升级攻略完整版
- 最新Windows11+Windows10系统各种版本永久激活密钥以及下载链接
- 想学Python,却还记不住语法?神仙书籍 python背记手册双手奉上
- 如何用Python语言开发大型服务器程序
- 30天Python 入门到精通(python零基础入门到精通)
- 入门扫盲:9本自学Python PDF书籍,让你避免踩坑,轻松变大神!
- 学好Python需要看的4本书推荐(学python好用的书)
- 标签列表
-
- spire.doc (59)
- system.data.oracleclient (61)
- 按键小精灵源码提取 (66)
- pyqt5designer教程 (65)
- 联想刷bios工具 (66)
- c#源码 (64)
- graphics.h头文件 (62)
- mysqldump下载 (66)
- sqljdbc4.jar下载 (56)
- libmp3lame (60)
- maven3.3.9 (63)
- 二调符号库 (57)
- 苹果ios字体下载 (56)
- git.exe下载 (68)
- diskgenius_winpe (72)
- pythoncrc16 (57)
- solidworks宏文件下载 (59)
- qt帮助文档中文版 (73)
- satacontroller (66)
- hgcad (64)
- bootimg.exe (69)
- android-gif-drawable (62)
- axure9元件库免费下载 (57)
- libmysqlclient.so.18 (58)
- springbootdemo (64)
本文暂时没有评论,来添加一个吧(●'◡'●)