JDK8 - Date

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 callable = new Callable() {
            @Override
            public Date call() throws Exception {
                //synchronized同步代码块解决线程不安全的问题,java.lang.NumberFormatException是因线程不安全造成的
                synchronized (sdf){
                    return sdf.parse("20200215");
                }
            }
        };

        List> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future task = pool.submit(callable);
            list.add(task);
        }

        for (Future 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 callable = new Callable() {
            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("20200215",dtf);
            }
        };

        List> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future task = pool.submit(callable);
            list.add(task);
        }

        for (Future 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 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();
    }
}

日期时间差

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();
    }
}
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-04-15

标签:差值   时间差   线程   字符串   时区   对象   日期   操作   时间   信息

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top