精华内容
参与话题
问答
  • LocalDateTime

    2019-12-13 13:43:59
    LocalDateTime\LocalDate\LocalTime 1.jdk1.8+ 2.Date和Calendar类都在java.util包下,新日期类在java.time包下 3.内部有一个私有的有参构造,不能new对象 4.常用方法 1.now():获取当前时间 2.of(int year, Month ...

    LocalDateTime\LocalDate\LocalTime

    1.jdk1.8+

    2.Date和Calendar类都在java.util包下,新日期类在java.time包下

    3.内部有一个私有的有参构造,不能new对象

    4.常用方法

    1.now():获取当前时间
    2.of(int year, Month month, int dayOfMonth, int Hour, int minute, int second):根据指定日期创建对象
    3.一系列getter方法:用于获取日期相关字段值
    4.提供了一系列plus方法:用于计算日期,每次计算都会返回一个新的对象,不会修改原来的对象
    5.format(DateTimeFormatter formatter):日期对象格式化为字符串

    DateTimeFormatter

    1.jdk1.8+

    2.DateFormat 和 SimpleDateFormat 都在java.text包下. DateTimeFormatter在java.time.format包下

    3.常用方法

    1.ofPattern(String pattern):根据指定格式化样式创建格式化器对象
    2.format(TemporalAccessor temporal):格式化指定日期对象

    4.LocalDateTime 和 Date 之间的转换

    补充类:Instant
    1.jdk1.8+
    2.瞬时类,时间戳,时刻类
    3.Date --> LocalDateTime
    4.LocalDateTime --> Date

    public class Demo01LocalDateTime {
        @Test
        public void test01(){
    
            LocalDateTime now = LocalDateTime.now();
            System.out.println(now);
    
            LocalDateTime ldt = LocalDateTime.of(2019, 12, 12, 10, 33, 30);
            System.out.println(ldt);
            System.out.println(ldt.getYear());
            System.out.println(ldt.getMonth().getValue());
            System.out.println(ldt.getDayOfMonth());
            System.out.println(ldt.getDayOfWeek().getValue());
            System.out.println(ldt.getDayOfYear());
    
            LocalDateTime newLdt = ldt.plusDays(7);
            System.out.println(newLdt);
    
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
    
            String nowStr1 = now.format(dtf);
            System.out.println(nowStr1);
    
            String nowStr = dtf.format(now);
            System.out.println(nowStr);
    
        }
    
        @Test
        public void test02(){
            // date --> localdatetime
            Date date = new Date();
            Instant instant = date.toInstant();
    
            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
            System.out.println(localDateTime);
        }
    
        @Test
        public void test03(){
            // localdatetime --> date
            LocalDateTime now = LocalDateTime.now();
            Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
    
            Date date = Date.from(instant);
            System.out.println(date);
        }
    
    }
    

    自定义日期工具类

    package org.jgs1904.util;
    
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.util.Date;
    
    /**
     * @ClassName MyDateUtil
     * @Description 自定义日期工具类
     * @Author RenYuWen
     * @Since 2019/12/12 10:05
     */
    public final class MyDateUtil {
    
        private MyDateUtil(){}
    
        /**
         * @Description: Date  转  LocalDateTime
         * @param: [date] Date对象
         * @return: java.time.LocalDateTime LocalDateTime对象
         * @author: RenYuWen
         * @date: 2019/12/12 10:10
         */
        public static LocalDateTime dateToLocalDateTime(Date date){
            LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            return localDateTime;
        }
    
        /**
         * @Description: LocalDateTime 转  Date
         * @param: [localDateTime] LocalDateTime 对象
         * @return: java.util.Date Date 对象
         * @author: RenYuWen
         * @date: 2019/12/12 10:11
         */
        public static Date LocalDateTimeToDate(LocalDateTime localDateTime){
            Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            return date;
        }
    
    }
    
    
    展开全文
  • 本文目前提供:LocalDateTime获取时间戳(毫秒/秒)、LocalDateTime与String互转、Date与LocalDateTime互转 文中都使用的时区都是东8区,也就是北京时间。这是为了防止服务器设置时区错误时导致时间不对,如果您是...

    本文目前提供:LocalDateTime获取时间戳(毫秒/秒)、LocalDateTime与String互转、Date与LocalDateTime互转

    文中都使用的时区都是东8区,也就是北京时间。这是为了防止服务器设置时区错误时导致时间不对,如果您是其他时区,请自行修改

     

    1.LocalDateTime获取毫秒数

    //获取秒数
    Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
    //获取毫秒数
    Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
    
    

     

    2.LocalDateTime与String互转

    //时间转字符串格式化
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
     String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
    
    //字符串转时间
    String dateTimeStr = "2018-07-28 14:11:15";
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, df);

     

    3.Date与LocalDateTime互转

     

        //将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
        public static LocalDateTime dateConvertToLocalDateTime(Date date) {
            return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
        }
    
       
        //将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
        public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
            return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
        }
    
    
        /**
         * 测试转换是否正确
         */
        @Test
        public void testDateConvertToLocalDateTime() {
            Date date = DateUtils.parseDate("2018-08-01 21:22:22", DateUtils.DATE_YMDHMS);
            LocalDateTime localDateTime = DateUtils.dateConvertToLocalDateTime(date);
            Long localDateTimeSecond = localDateTime.toEpochSecond(ZoneOffset.of("+8"));
            Long dateSecond = date.toInstant().atOffset(ZoneOffset.of("+8")).toEpochSecond();
            Assert.assertTrue(dateSecond.equals(localDateTimeSecond));
        }

    想学习Python的Java老铁可关扫描下方猪哥vx公号

    展开全文
  • 基本概念时刻:所有计算机系统内部都用一个整数表示时刻,这个整数是距离格林尼治标准时间1970年1月1日0时0分0秒的毫秒数,可以理解时刻就是绝对时间,它与时区无关,不同时区对同一时刻的解读,即年月日时分秒是不...

     

    基本概念

    • 时刻:所有计算机系统内部都用一个整数表示时刻,这个整数是距离格林尼治标准时间1970年1月1日0时0分0秒的毫秒数,可以理解时刻就是绝对时间,它与时区无关,不同时区对同一时刻的解读,即年月日时分秒是不一样的;

    • 时区:同一时刻,世界上各个地区的时间可能是不一样的,具体时间与时区有关,一共有24个时区,英国格林尼治是0时区,北京是东八区,也就是说格林尼治凌晨1点,北京是早上9点;

    • 年历:我们都知道,中国有公历和农历之分,公历和农历都是年历,不同的年历,一年有多少月,每月有多少天,甚至一天有多少小时,这些可能都是不一样的,我们主要讨论公历。

    Java 8中表示日期和时间的类有多个,主要的有:

    • Instant:表示时刻,不直接对应年月日信息,需要通过时区转换

    • LocalDateTime: 表示与时区无关的日期和时间信息,不直接对应时刻,需要通过时区转换

    • LocalDate:表示与时区无关的日期,与LocalDateTime相比,只有日期信息,没有时间信息

    • LocalTime:表示与时区无关的时间,与LocalDateTime相比,只有时间信息,没有日期信息

    • ZonedDateTime: 表示特定时区的日期和时间

    • ZoneId/ZoneOffset:表示时区

    import java.time.*;
    import java.time.format.DateTimeFormatter;
    import java.util.Date;
    
    public class Main {
    
        public static void main(String[] args) {
    
            String nowDateStr = LocalDate.now().toString();
            System.out.println(nowDateStr);//2018-03-27
    
            LocalDate nowDate = LocalDate.parse("2018-03-25");
            System.out.println(nowDate.toString());//2018-03-25
    
    
            String nowTimeStr = LocalTime.now().toString();
            System.out.println(nowTimeStr);//13:45:07.105
    
            LocalTime nowTime = LocalTime.parse("12:10:13");
            System.out.println(nowTime.toString());//12:10:13
    
            System.out.println(LocalDateTime.now().toString());//2018-03-27T13:55:34.047
            System.out.println(LocalDateTime.now().toLocalDate().toString());//2018-03-27
            System.out.println(LocalDateTime.now().toLocalTime().toString());//13:55:34.047
    
            System.out.println(LocalDateTime.MAX.toString());//+999999999-12-31T23:59:59.999999999
            System.out.println(LocalDateTime.MIN.toString());//-999999999-01-01T00:00
    
            new Main().date2LocalDateTime(new Date());
            new Main().localDateTime2Date(LocalDateTime.now());
        }
    
    
        /**
         * Date转换为LocalDateTime
         * @param date
         */
        public void date2LocalDateTime(Date date){
            Instant instant = date.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
            ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
    
            System.out.println(localDateTime.toString());//2018-03-27T14:07:32.668
            System.out.println(localDateTime.toLocalDate() + " " +localDateTime.toLocalTime());//2018-03-27 14:48:57.453
    
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//This class is immutable and thread-safe.@since 1.8
            System.out.println(dateTimeFormatter.format(localDateTime));//2018-03-27 14:52:57
        }
    
        /**
         * LocalDateTime转换为Date
         * @param localDateTime
         */
        public void localDateTime2Date( LocalDateTime localDateTime){
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
            Date date = Date.from(zdt.toInstant());
            System.out.println(date.toString());//Tue Mar 27 14:17:17 CST 2018
        }
    
    }
    

     

    更多请详见:http://www.cnblogs.com/qinersky902/p/7232163.html

    欢迎关注我的公众号

    展开全文
  • LocalDateTime documentation

    2020-11-26 18:17:34
    s some initial documentation for LocalDateTime. I have new respect for technical writers who do this for a living... it's hard! Fixes #904. <p>One thing I wasn't quite sure about was the ...
  • <div><p>validation error on java.time.LocalDateTime: <p>for example: "lastUpdated": "2018-11-15T21:08:59", <p>validation error: {"statusCode":400,"code":"ERR11004&...
  • <div><p>In my ZonedAbsolute brainstorm, I had suggested that the LocalDateTime type be a pure wrapper over Absolute and TimeZone. Fields like "year" and "hour" would not be accessible ...
  • <div><p>Validation of <code>java.util.Date</code> is more strict than the validation of <code>LocalDateTime</code>. Example see below. Before PrimeFaces 8 I was using a custom Converter which sets ...
  • <div><p>The following shows that a <code>LocalDateTime</code> is always always tethered to the current time zone during insertion. ...<p>This is incorrect. A <code>timestamp</code> column has <strong><em...
  • <p><strong>LocalDateTime</strong> values get wrapped in additional <code>"</code> quotes on serialization and fail deserialization if not quoted (e.g.<code>"\"2014-12-20T02:30:10\""...
  • LocalDateTime用法大全

    千次阅读 2020-01-29 19:52:21
    常规使用 LocalDateTime now = LocalDateTime.now(); // 2020-01-29T14:35:51.207 int year = now.getYear(); // 2020 Month month = now.getMonth(); // JANUARY int monthValue = now...

    常规使用

    LocalDateTime now = LocalDateTime.now();   // 2020-01-29T14:35:51.207
    int year = now.getYear();                  // 2020
    Month month = now.getMonth();              // JANUARY
    int monthValue = now.getMonthValue();      // 1
    int dayOfYear = now.getDayOfYear();        // 29
    int dayOfMonth = now.getDayOfMonth();      // 29
    DayOfWeek dayOfWeek = now.getDayOfWeek();  // WEDNESDAY
    int dayOfWeekValue = dayOfWeek.getValue(); // 3
    int hour = now.getHour();                  // 14
    int minute = now.getMinute();              // 35
    int second = now.getSecond();              // 51
    
    long seconds = Instant.now().getEpochSecond();    // 秒时间戳(10位)
    long milliSeconds = Instant.now().toEpochMilli(); // 毫秒时间戳(13位)
    
    LocalDateTime dateTimeFromSecond = LocalDateTime.ofInstant(
        Instant.ofEpochSecond(seconds), ZoneOffset.ofHours(8)
    );  // 秒转datetime
    
    LocalDateTime dateTimeFromMilliSecond = LocalDateTime.ofInstant(
        Instant.ofEpochMilli(milliSeconds), ZoneOffset.ofHours(8)
    ); // 毫秒转datetime
    

    各种转换

    String format = LocalDateTime.now().format(
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    );  // datetime转字符串
    
    LocalDateTime dateTime = LocalDateTime.parse(
        format,
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    );  // 字符串转datetime
    
    Date date = Date.from(dateTime.toInstant(ZoneOffset.ofHours(8)));                             // datetime转date
    LocalDateTime fromDate = date.toInstant().atOffset(ZoneOffset.ofHours(8)).toLocalDateTime();  // date转datetime
    

    自定义日期 / 日期加减

    LocalDateTime dateTime = LocalDateTime.of(2020, 1, 29, 14, 35, 51); // 2020-01-29T14:35:51
    
    LocalDateTime localDateTime1 = dateTime.minusSeconds(1);            // 2020-01-29T14:35:50
    LocalDateTime localDateTime2 = dateTime.minusMinutes(1);            // 2020-01-29T14:34:51
    LocalDateTime localDateTime3 = dateTime.minusHours(1);              // 2020-01-29T13:35:51
    LocalDateTime localDateTime4 = dateTime.minusDays(1);               // 2020-01-28T14:35:51
    LocalDateTime localDateTime5 = dateTime.minusWeeks(1);              // 2020-01-22T14:35:51
    LocalDateTime localDateTime6 = dateTime.minusMonths(1);             // 2019-12-29T14:35:51
    LocalDateTime localDateTime7 = dateTime.minusYears(1);              // 2019-01-29T14:35:51
    

    增加的为对应的plus函数,如dateTime.plusSeconds(1)

    比较日期

    LocalDateTime now = LocalDateTime.now();     // 2020-01-29T14:35:51.207
    LocalDateTime yesterday = now.minusDays(1);  // 2020-01-28T14:35:51.207
    boolean after = now.isAfter(yesterday);      // true
    boolean before = now.isBefore(yesterday);    // false
    boolean equal = now.isEqual(yesterday);      // false
    

    其他类

    LocalDate日期

    LocalDate dateNow = LocalDate.now();        // 2020-01-29
    LocalDate date = LocalDate.of(2020, 1, 29); // 2020-01-29
    

    LocalTime时间

    LocalTime timeNow = LocalTime.now();       // 14:35:51.207
    LocalTime time = LocalTime.of(23, 59, 59); // 23:59:59
    

    LocalDateTime日期时间

    LocalDateTime dateTimeNow = LocalDateTime.now();                    // 2020-01-29T14:35:51.207
    LocalDateTime dateTime = LocalDateTime.of(2020, 1, 29, 23, 59, 59); // 2020-01-29T23:59:59
    

    Instant时刻

    long second = Instant.now().getEpochSecond();          // 1580279751
    long milliSecond = Instant.now().toEpochMilli();       // 1580279751000
    Instant instant1 = Instant.ofEpochSecond(second);     // 2020-01-29T14:35:51Z
    Instant instant2 = Instant.ofEpochMilli(milliSecond); // 2020-01-29T14:35:51.207Z
    

    Duration时间差

    Duration duration = Duration.between(
        LocalDateTime.now(), LocalDateTime.now().plusDays(1)
    );  // PT24H
    long seconds = duration.getSeconds();             // 86400
    long seconds2 = duration.get(ChronoUnit.SECONDS); // 86400
    
    Duration ofDays = Duration.ofDays(1);             // PT24H
    Duration ofHours = Duration.ofHours(1);           // PT1H
    Duration ofMinutes = Duration.ofMinutes(1);       // PT1M
    Duration ofSeconds = Duration.ofSeconds(1);       // PT1S
    

    Period时间段

    Period between = Period.between(
        LocalDate.of(2020, 1, 22), LocalDate.of(2020, 2, 9)
    ); // P18D
    int year = between.getYears();   // 0
    int month = between.getMonths(); // 0
    int day = between.getDays();     // 18
    
    Period period = Period.of(1, 2, 3); // P1Y2M3D
    long years = period.get(ChronoUnit.YEARS);            // 1
    long months = period.get(ChronoUnit.MONTHS);          // 2
    long days = period.get(ChronoUnit.DAYS);              // 3
    

    Clock时钟

    Clock clock1 = Clock.system(ZoneOffset.ofHours(8));  // SystemClock[+08:00]
    Clock clock2 = Clock.systemUTC();                    // SystemClock[Z]
    
    long millis1 = clock1.millis();      // 1582285924008
    long millis2 = clock2.millis();      // 1582285924008
    Instant instant1 = clock1.instant(); // 2020-02-21T11:54:58.427Z
    Instant instant2 = clock2.instant(); // 2020-02-21T11:54:58.428Z
    
    展开全文
  • Java8中的LocalDateTime工具类

    万次阅读 多人点赞 2017-07-22 22:57:14
    网上搜索了半天都没有找到Java8的LocalDateTime的工具类,只好自己写了一个,常用功能基本都有。还在用Date的Java同道该换换了。 个人项目地址:https://github.com/KingBoyWorld/common.git,Common模块中有很多...
  • <p><code>LocalDateTime.ofInstant(1459546270798)</code></p> <p>I get the following stacktrace: <p>TypeError: localDateTime.toEpochSecond is not a function at SystemDefaultZoneRules....
  • <p>When testing object mapping, it can be useful to compare <code>LocalDateTime</code> with <code>XMLGregorianCalendar</code> without having to compare field by field or via a filed extractor ...
  • Temporal.LocalDateTime.from({ year: 1933, month: 1, day: 1, timeZone: singapore }); ldt.hoursInDay // => ??? </code></pre> <p>Neither 23 nor 24 are what a user would expect, it seems to me....
  • LocalDateTime和Date 本篇文章你将了解到: 为什么需要LocalDate、LocalTime、LocalDateTime【java8新提供的类】 java8新的时间API的使用方式,包括创建、格式化、解析、计算、修改 为什么需要LocalDate...
  • 为什么建议使用你LocalDateTime,而不是Date?

    万次阅读 多人点赞 2019-09-12 10:52:22
    在项目开发过程中经常遇到时间处理,... 为什么需要LocalDate、LocalTime、LocalDateTime【java8新提供的类】 java8新的时间API的使用方式,包括创建、格式化、解析、计算、修改 为什么需要LocalDate、Loc...
  • <p>Yes, <code>LocalDateTime</code> is now inserted and retrieved without regard for any current time zone. Which, in my interpretation, is the correct thing to do. <ul><li>[x] Have you added an ...
  • t seem to be any good <code>LocalDate</code> and <code>LocalDateTime</code> axis types. Would this be something that's in scope for this library? <p>I'm coming across this need a lot as I ...

空空如也

1 2 3 4 5 ... 20
收藏数 4,383
精华内容 1,753
关键字:

localdatetime