精华内容
下载资源
问答
  • 解决方案 You're probably looking for LocalDate(Object). It's a bit confusing since it takes a generic Object, but the docs indicate that it will use a ConverterManager that knows how to handle a ...

    How to specify the format string to convert the date alone from string. In my case, only the date part is relevant

    Constructing it as DateTime fails:

    String dateString = "2009-04-17";

    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");

    DateTime dateTime = formatter.parseDateTime(dateString);

    with error java.lang.IllegalArgumentException: Invalid format: "2011-04-17" is too short

    Probably because I should use LocalDate instead. But, I do not see any formatter for LocalDate . What is the best way to convert String dateString = "2009-04-17"; into LocalDate (or something else if that is not the right representation)

    thanks...

    解决方案

    You're probably looking for LocalDate(Object). It's a bit confusing since it takes a generic Object, but the docs indicate that it will use a ConverterManager that knows how to handle a String if you pass a String to the constructor, e.g.

    LocalDate myDate = new LocalDate("2010-04-28");

    展开全文
  • 这是将java.util.Date转换为java.time.LocalDate的代码。 Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // different way of create ...

    这是将java.util.Date转换为java.time.LocalDate的代码。

    Date date = new Date();
      LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    
      // different way of create instant object
      LocalDate localDate = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();

    java.util.Date转换为java.time.LocalDateTime

    Date date = new Date();
      LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

    java.util.Date转换为java.time.ZonedDateTime

    Date date = new Date();
      ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());

    对于java.sql.Date ,我们可以直接将其转换。

    java.sql.Date sqlDate = java.sql.Date.valueOf("2020-02-05");
      LocalDate localDate2 = sqlDate.toLocalDate();

    1.日期-> java.time.LocalDate

    java.util.Date没有时区的概念,仅表示自Unix纪元时间– 1970-01-01T00:00:00Z(格林尼治标准时间(GMT / UTC)1970年1月1日开始的午夜)以来经过的秒数。

    注意
    新的Java 8 java.time.Instant是经典java.util.Date的等效类。

    日期转换的想法是转换为带有时区的瞬间。

    Date -> Instant + System default time zone = LocalDate
    Date -> Instant + System default time zone = LocalDateTime
    Date -> Instant + System default time zone = ZonedDateTime
    DateToJavaTime.java
    package com.mkyong.java8;
    
    import java.time.Instant;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    import java.util.Date;
    
    public class DateToJavaTime {
    
        public static void main(String[] args) {
    
            //Asia/Kuala_Lumpur +8
            ZoneId defaultZoneId = ZoneId.systemDefault();
            System.out.println("System Default TimeZone : " + defaultZoneId);
    
            //toString() append +8 automatically.
            Date date = new Date();
            System.out.println("date : " + date);
    
            //1. Convert Date -> Instant
            Instant instant = date.toInstant();
            System.out.println("instant : " + instant); //Zone : UTC+0
    
            //2. Instant + system default time zone + toLocalDate() = LocalDate
            LocalDate localDate = instant.atZone(defaultZoneId).toLocalDate();
            System.out.println("localDate : " + localDate);
    
            //3. Instant + system default time zone + toLocalDateTime() = LocalDateTime
            LocalDateTime localDateTime = instant.atZone(defaultZoneId).toLocalDateTime();
            System.out.println("localDateTime : " + localDateTime);
    
            //4. Instant + system default time zone = ZonedDateTime
            ZonedDateTime zonedDateTime = instant.atZone(defaultZoneId);
            System.out.println("zonedDateTime : " + zonedDateTime);
    
        }
    
    }

    输出量

    System Default TimeZone : Asia/Kuala_Lumpur
    
    date : Fri Aug 19 21:46:31 MYT 2016
    instant : 2016-08-19T13:46:31.981Z
    
    localDate : 2016-08-19
    localDateTime : 2016-08-19T21:46:31.981
    zonedDateTime : 2016-08-19T21:46:31.981+08:00[Asia/Kuala_Lumpur]

    2. java.time.LocalDate->日期

    本示例说明如何将LocalDateLocalDateTimeZonedDateTime转换回经典的java.util.Date

    JavaTimeToDate.java
    package com.mkyong.java8;
    
    import java.time.*;
    import java.util.Date;
    
    public class JavaTimeToDate {
    
        public static void main(String[] args) {
    
            //Asia/Kuala_Lumpur +8
            ZoneId defaultZoneId = ZoneId.systemDefault();
            System.out.println("System Default TimeZone : " + defaultZoneId);
    
            LocalDate localDate = LocalDate.of(2016, 8, 19);
            Date date = Date.from(localDate.atStartOfDay(defaultZoneId).toInstant());
            System.out.println("\n1. LocalDate -> Date");
            System.out.println("localDate : " + localDate);
            System.out.println("date : " + date);
    
            LocalDateTime localDateTime = LocalDateTime.of(2016,8,19,21,46,31);
            Date date2 = Date.from(localDateTime.atZone(defaultZoneId).toInstant());
            System.out.println("\n2. LocalDateTime -> Date");
            System.out.println("localDateTime : " + localDateTime);
            System.out.println("date2 : " + date2);
    
            ZonedDateTime zonedDateTime = localDateTime.atZone(defaultZoneId);
            Date date3 = Date.from(zonedDateTime.toInstant());
            System.out.println("\n3. ZonedDateTime -> Date");
            System.out.println("zonedDateTime : " + zonedDateTime);
            System.out.println("date3 : " + date3);
    
        }
    
    }

    输出量

    System Default TimeZone : Asia/Kuala_Lumpur
    
    1. LocalDate -> Date
    localDate : 2016-08-19
    date : Fri Aug 19 00:00:00 MYT 2016
    
    2. LocalDateTime -> Date
    localDateTime : 2016-08-19T21:46:31
    date2 : Fri Aug 19 21:46:31 MYT 2016
    
    3. ZonedDateTime -> Date
    zonedDateTime : 2016-08-19T21:46:31+08:00[Asia/Kuala_Lumpur]
    date3 : Fri Aug 19 21:46:31 MYT 2016

    常见问题

    问题:如果“日期”没有时区概念,那么如果我们打印出“日期”对象,为什么会显示时区? 例如 :

    //Fri Aug 19 11:52:06 MYT 2016
      System.out.println(new Date()); //MYT = my system default time zone

    :检查java.uti.Date.toString()源代码,如果打印出Date对象,则将附加系统默认时区并一起显示。

    java.util.Date
    public String toString() {
    
            //...omitted...
    
            TimeZone zi = date.getZone();
            if (zi != null) {
                sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
            } else {
                sb.append("GMT");
            }
            sb.append(' ').append(date.getYear());  // yyyy
            return sb.toString();
    }

    注意
    自JDK1.1起,此行为是设计缺陷。 这引起很多混乱。 同样, java.util.Date不存储任何时区信息,但是如果您将其打印出来,则系统默认时区将一起显示。

    参考文献

    翻译自: https://mkyong.com/java8/java-8-convert-date-to-localdate-and-localdatetime/

    展开全文
  • Java LocalDate

    2020-07-13 23:34:52
    Java LocalDate class is part of Java 8 Date API. Java LocalDate类是Java 8 Date API的一部分。 Java LocalDate (Java LocalDate) Java LocalDate is immutable class and hence thread safe. Java LocalDate是...

    Java LocalDate class is part of Java 8 Date API.

    Java LocalDate类是Java 8 Date API的一部分。

    Java LocalDate (Java LocalDate)

    • Java LocalDate is immutable class and hence thread safe.

      Java LocalDate是不可变的类 ,因此是线程安全的
    • LocalDate provides date output in the format of YYYY-MM-dd.
      Java LocalDate

      LocalDate以YYYY-MM-dd格式提供日期输出。
    • The LocalDate class has no time or Timezone data. So LocalDate is suitable to represent dates such as Birthday, National Holiday etc.

      LocalDate类没有时间或时区数据。 因此LocalDate适合代表生日,国定假日等日期。
    • LocalDate class implements Temporal, TemporalAdjuster, ChronoLocalDate and Serializable interfaces.

      LocalDate类实现TemporalTemporalAdjusterChronoLocalDateSerializable接口。
    • LocalDate is a final class, so we can’t extend it.

      LocalDate是最后一个类,因此我们无法扩展它。
    • LocalDate is a value based class, so we should use equals() method for comparing if two LocalDate instances are equal or not.

      LocalDate是一个基于值的类,因此我们应该使用equals()方法比较两个LocalDate实例是否相等。

    导入Java LocalDate类 (Importing Java LocalDate Class)

    Java LocalDate class is in java.time package. So you can import it using import statement:

    Java LocalDate类在java.time包中。 因此,您可以使用import语句将其导入:

    import java.time.LocalDate;

    创建LocalDate实例 (Creating LocalDate instance)

    There are four standard ways to create LocalDate instance.

    有四种创建LocalDate实例的标准方法。

    1. Invoking the static now() method that returns the current date from system clock.
      LocalDate ldObj = LocalDate.now();
      		
      System.out.println(ldObj); //prints "2017-11-10"

      调用静态now()方法从系统时钟返回当前日期。
    2. By passing Year, Month, and Day values to LocalDate of() method
      LocalDate ldObj = LocalDate.of(2017, 11, 6);
      		
      System.out.println(ldObj); //prints "2017-11-06"

      通过将Year,Month和Day值传递给LocalDate of()方法
    3. Using LocalDate parse() method.
      LocalDate ld = LocalDate.parse("2017-11-10");

      使用LocalDate parse()方法。
    4. Using LocalDate ofInstant() method as shown below.
      LocalDate ld = LocalDate.ofInstant(Instant.now(), ZoneId.systemDefault());

      使用LocalDate ofInstant()方法,如下所示。

    从LocalDate类检索日期信息 (Retrieving Date Information from LocalDate Class)

    Java LocalDate class provides a lot of useful methods to get the more details about date, for example year, month, day of year etc. Let’s look into these through some example programs.

    Java LocalDate类提供了许多有用的方法来获取有关日期的更多详细信息,例如年,月,日等。让我们通过一些示例程序来研究这些内容。

    1. getYear(): returns the year contained within the LocalDate object.
      LocalDate ld = LocalDate.of(2017, 11, 10);
      		
      int year = ld.getYear();
      		
      System.out.println(year); //prints "2017"

      getYear() :返回LocalDate对象中包含的年份。
    2. getMonth(): returns the month contained within the LocalDate object.
      LocalDate ld = LocalDate.now(); // today is 10-Nov-2017
      
      Month month = ld.getMonth();
      
      System.out.println(month + "," + month.getValue()); // prints "NOVEMBER,11"

      getMonth() :返回LocalDate对象中包含的月份。
    3. getDayOfMonth(): returns the day of the month contained within the LocalDate object.
      LocalDate ld = LocalDate.now(); // today is 10-Nov-2017
      
      int dayOfMonth = ld.getDayOfMonth();
      
      System.out.println(dayOfMonth); // prints "10"

      getDayOfMonth() :返回LocalDate对象中包含的月份中的一天。
    4. getDayOfWeek(): returns the day of the week from the LocalDate object.
      LocalDate ld = LocalDate.now(); // today is 10-Nov-2017
      
      DayOfWeek dayOfWeek = ld.getDayOfWeek();
      
      System.out.println(dayOfWeek + "," + dayOfWeek.getValue()); // prints "FRIDAY,5"

      getDayOfWeek() :从LocalDate对象返回星期几。
    5. getDayOfYear(): returns the day of the year from the LocalDate instance.
      LocalDate ld = LocalDate.of(2017, 2, 10);
      
      int dayOfYear = ld.getDayOfYear();
      
      System.out.println(dayOfYear); // prints "41" i.e. 31+10

      getDayOfYear() :从LocalDate实例返回一年中的一天。

    Java LocalDate方法–加号和减号 (Java LocalDate methods – plus and minus)

    1. plusYears(long yearsToAdd): adds the yearsToAdd to the year value and return the copy of LocalDate object. Since LocalDate is immutable, the specified object doesn’t change. Also if the new date is invalid then the last valid date is returned.
      LocalDate ld = LocalDate.of(2017, 2, 10);
      
      LocalDate ldNew = ld.plusYears(3);
      
      System.out.println(ldNew + ":" + ld); // prints "2020-02-10:2017-02-10"
      
      ld = LocalDate.of(2016, 2, 29);
      ldNew = ld.plusYears(1); // 2017-02-29 is invalid date, so it will return 2017-02-28
      System.out.println(ldNew); // prints "2017-02-28"

      plusYears(long yearsToAdd) :将yearsToAdd添加到年份值并返回LocalDate对象的副本。 由于LocalDate是不可变的,因此指定的对象不会更改。 同样,如果新日期无效,则返回最后一个有效日期。
    2. plusWeeks(long weeksToAdd): returns a new LocalDate instance after adding weeksToAdd weeks, no change in the specified object.
      LocalDate ld = LocalDate.of(2017, 11, 10);
      
      LocalDate ldNew = ld.plusWeeks(3);
      
      System.out.println(ldNew); // 2017-12-01

      plusWeeks(long weeksToAdd) :在添加weeksToAdd周之后,返回一个新的LocalDate实例,指定对象没有变化。
    3. plusMonths(long monthsToAdd): returns a copy of specified LocalDate object after adding monthsToAdd months.
      LocalDate ld = LocalDate.of(2017, 11, 10);
      
      LocalDate ldNew = ld.plusMonths(3);
      
      System.out.println(ldNew); // 2018-02-10

      plusMonths(long monthsToAdd) :添加monthsToAdd months后,返回指定LocalDate对象的副本。
    4. plusDays(long daysToAdd): returns a copy of specified LocalDate object after adding daysToAdd days.
      LocalDate ld = LocalDate.of(2017, 11, 10);
      
      LocalDate ldNew = ld.plusDays(10);
      
      System.out.println(ldNew); // 2017-11-20

      plusDays(long daysToAdd) :添加daysToAdd天后,返回指定LocalDate对象的副本。
    5. minusDays(long daysToSubtract): returns a copy of specified LocalDate object after subtracting daysToSubtract days.
      LocalDate ld = LocalDate.of(2017, 11, 10);
      
      LocalDate ldNew = ld.minusDays(10);
      
      System.out.println(ldNew); // 2017-10-31

      minusDays(long daysToSubtract) :减去daysToSubtract days之后,返回指定LocalDate对象的副本。
    6. minusWeeks(long weeksToSubtract): returns a copy of specified LocalDate object after subtracting weeksToSubtract weeks.
      LocalDate ld = LocalDate.of(2017, 11, 10);
      
      LocalDate ldNew = ld.minusWeeks(1);
      
      System.out.println(ldNew); // 2017-11-03

      minusWeeks(long weeksToSubtract) :在减去weeksToSubtract周之后,返回指定LocalDate对象的副本。
    7. minusMonths(long monthsToSubtract): returns a copy of specified LocalDate object after subtracting monthsToSubtract months.
      LocalDate ld = LocalDate.of(2017, 11, 10);
      
      LocalDate ldNew = ld.minusMonths(1);
      
      System.out.println(ldNew); // 2017-10-10

      minusMonths(long monthsToSubtract) :减去monthsToSubtract months之后,返回指定LocalDate对象的副本。
    8. minusYears(long yearsToSubtract): returns a copy of specified LocalDate object after subtracting yearsToSubtract years. If the new LocalDate is invalid (29-Feb), then last valid date is returned.
      LocalDate ld = LocalDate.of(2016, 2, 29);
      
      LocalDate ldNew = ld.minusYears(2);
      
      System.out.println(ldNew); // 2014-02-28

      minusYears(long yearsToSubtract) :减去yearsToSubtract years之后,返回指定LocalDate对象的副本。 如果新的LocalDate无效(2月29日),则返回上一个有效日期。

    迄今为止的Java LocalDate (Java LocalDate to Date)

    We should avoid using legacy java.util.Date class but sometimes we have to convert LocalDate to Date for legacy support. Below are two ways to convert LocalDate to Date, you can use any of them.

    我们应该避免使用旧版java.util.Date类,但有时我们必须将LocalDate转换为Date以获取旧版支持。 以下是将LocalDate转换为Date的两种方法,您可以使用其中任何一种。

    package com.journaldev.java;
    
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.util.Date;
    
    public class JavaLocalDateExample {
    
    	public static void main(String args[]) {
    
    		LocalDate ld = LocalDate.now();
    
    		Date date = Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant());
    
    		System.out.println(date); // prints "Fri Nov 10 00:00:00 IST 2017"
    		
    		Date date1 = java.sql.Date.valueOf(ld);
    		
    		System.out.println(date1); // prints "2017-11-10"
    	}
    }

    That’s all for java LocalDate class.

    Java LocalDate类就这些了。

    References: API Doc, StackOverflow Article

    参考: API DocStackOverflow文章

    翻译自: https://www.journaldev.com/16896/java-localdate

    展开全文
  • LocalDate of = LocalDate.of(2020, 8, 20); LocalDate of1 = LocalDate.of(2020, 11, 2); Period until = of.until(of1);//计算差几月零几天 long until = of.until(of1, ChronoUnit.MONTH...

            LocalDate of = LocalDate.of(2020, 8, 20);
            LocalDate of1 = LocalDate.of(2020, 11, 2);
            Period until = of.until(of1);//计算差几月零几天
            long until = of.until(of1, ChronoUnit.MONTHS);//计算差多少年、月、天。
            
            //Date 转LocalDate
            LocalDate start = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).toLocalDate();
            //LocalDate 转Date
            Date date = Date.from( of.atTime(0,0).atZone( ZoneId.systemDefault()).toInstant());
            
            //long转LocalDateTime
            long start;
            LocalDateTime st = LocalDateTime.ofInstant(Instant.ofEpochMilli(start), ZoneId.systemDefault());
            //字符串转LocalDatetime
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime begin = LocalDateTime.parse("2018-08-09 15:18:20", dateTimeFormatter);
            
            //大小比较
            of.isBefore(of1);
            实体转jsonArray
            com.alibaba.fastjson.JSONArray jsonArray = com.alibaba.fastjson.JSONObject.parseArray(com.alibaba.fastjson.JSONObject.toJSONString(incomeParticularsDTOS));
            jsonArray转实体
            List<RouteDefinition> routeDefinitions = JSON.parseArray(configInfo, RouteDefinition.class);
            实体转json再转map
            Map<String, Object> voJson = com.alibaba.fastjson.JSONObject.parseObject(JSON.toJSONString(vo), new TypeReference<Map<String, Object>>() {});
            字符串转json
            JSONObject rentFreeJson = JSON.parseObject(this.rentFree);

    展开全文
  • Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互 Java8中 java.util.Date 类新增了两个方法,分别是from(Instant instant)和toInstant()方法 // Obtains an instance of Date from an Instant ...
  • } @Override public String print(LocalDate object, Locale locale) { return DateTimeFormatter.ISO_LOCAL_DATE.format(object); } }; } @Bean public Formatter localDateTimeFormatter() { return new ...
  • Java 8中 java.util.Date 类新增了两个方法,分别是from(Instant instant)和toInstant()...// Obtains an instance of Date from an Instant object. public static Date from(Instant instant) {  try {  return
  • Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互 Java 8中 java.util.Date 类新增了两个方法,分别是from(Instant instant)和toInstant()方法 // Obtains an instance of Date from an Instant object. ...
  • 背景前端和后端在时间格式的传递上都走的是时间戳(方便前端自由定制)时间格式大多用的是LocalDate,并不是传统的Date简单来说就是时间戳在各类形式下日期类。当有如下类似代码的时候,后端该做哪些配置来满足上述...
  • 0x0 背景 项目中使用LocalDateTime系列作为dto中时间的类型,但是spring收到参数后总报错,为了...PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam、PathVariable等)都没加,也是会出错的...
  • java日期对象 LocalDate

    2021-07-27 12:18:59
    java8新API LocalDate LocalDate和LocalDateTime在实际开发中很常用,因为实体类中往往会存在日期时间字段。 类方法: 1、LocalDate.now() ...获取当前时间,返回的是LoCalDate... LocalDate localDate = LocalDa..
  • 将java.util.Date转换为java.time.LocalDate

    千次阅读 2020-05-05 11:20:28
    What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDat

空空如也

空空如也

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

object转localdate