// the current date
LocalDate currentDate = LocalDate.now();
// 2014-02-10
LocalDate tenthFeb2014 = LocalDate.of(
2014
, Month.FEBRUARY,
10
);
// months values start at 1 (2014-08-01)
LocalDate firstAug2014 = LocalDate.of(
2014
,
8
,
1
);
// the 65th day of 2010 (2010-03-06)
LocalDate sixtyFifthDayOf2010 = LocalDate.ofYearDay(
2010
,
65
);
LocalTime and LocalDateTime are the next classes we look at. Both work similar to LocalDate. A LocalTime works with time (without dates) while LocalDateTime combines date and time in one class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
LocalTime currentTime = LocalTime.now(); // current time
LocalTime midday = LocalTime.of( 12 , 0 ); // 12:00
LocalTime afterMidday = LocalTime.of( 13 , 30 , 15 ); // 13:30:15
// 12345th second of day (03:25:45) LocalTime fromSecondsOfDay = LocalTime.ofSecondOfDay( 12345 );
// dates with times, e.g. 2014-02-18 19:08:37.950 LocalDateTime currentDateTime = LocalDateTime.now(); // 2014-10-02 12:30 LocalDateTime secondAug2014 = LocalDateTime.of( 2014 , 10 , 2 , 12 , 30 );
// 2014-12-24 12:00 LocalDateTime christmas2014 = LocalDateTime.of( 2014 , Month.DECEMBER, 24 , 12 , 0 );
|
By default LocalDate/Time classes will use the system clock in the default time zone. We can change this by providing a time zone or an alternative Clock implementation:
1
2
3
4
5
|
// current (local) time in Los Angeles LocalTime currentTimeInLosAngeles = LocalTime.now(ZoneId.of( "America/Los_Angeles" ));
// current time in UTC time zone LocalTime nowInUtc = LocalTime.now(Clock.systemUTC()); |
From LocalDate/Time objects we can get all sorts of useful information we might need. Some examples:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
LocalDate date = LocalDate.of( 2014 , 2 , 15 ); // 2014-02-15
boolean isBefore = LocalDate.now().isBefore(date); // false
// information about the month Month february = date.getMonth(); // FEBRUARY
int februaryIntValue = february.getValue(); // 2
int minLength = february.minLength(); // 28
int maxLength = february.maxLength(); // 29
Month firstMonthOfQuarter = february.firstMonthOfQuarter(); // JANUARY
// information about the year int year = date.getYear(); // 2014
int dayOfYear = date.getDayOfYear(); // 46
int lengthOfYear = date.lengthOfYear(); // 365
boolean isLeapYear = date.isLeapYear(); // false
DayOfWeek dayOfWeek = date.getDayOfWeek(); int dayOfWeekIntValue = dayOfWeek.getValue(); // 6
String dayOfWeekName = dayOfWeek.name(); // SATURDAY
int dayOfMonth = date.getDayOfMonth(); // 15
LocalDateTime startOfDay = date.atStartOfDay(); // 2014-02-15 00:00
// time information LocalTime time = LocalTime.of( 15 , 30 ); // 15:30:00
int hour = time.getHour(); // 15
int second = time.getSecond(); // 0
int minute = time.getMinute(); // 30
int secondOfDay = time.toSecondOfDay(); // 55800
|
Some information can be obtained without providing a specific date. For example, we can use the Year class if we need information about a specific year:
1
2
3
4
5
6
7
|
Year currentYear = Year.now(); Year twoThousand = Year.of( 2000 );
boolean isLeap = currentYear.isLeap(); // false
int length = currentYear.length(); // 365
// sixtyFourth day of 2014 (2014-03-05) LocalDate date = Year.of( 2014 ).atDay( 64 );
|
We can use the plus and minus methods to add or subtract specific amounts of time. Note that these methods always return a new instance (Java 8 date/time classes are immutable).
1
2
3
4
|
LocalDate tomorrow = LocalDate.now().plusDays( 1 );
// before 5 houres and 30 minutes LocalDateTime dateTime = LocalDateTime.now().minusHours( 5 ).minusMinutes( 30 );
|
TemporalAdjusters are another nice way for date manipulation. TemporalAdjuster is a single method interface that is used to separate the process of adjustment from actual date/time objects. A set of common TemporalAdjusters can be accessed using static methods of the TemporalAdjusters class.
1
2
3
4
5
6
7
|
LocalDate date = LocalDate.of( 2014 , Month.FEBRUARY, 25 ); // 2014-02-25
// first day of february 2014 (2014-02-01) LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth()); // last day of february 2014 (2014-02-28) LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth()); |
Static imports make this more fluent to read:
1
2
3
4
5
6
7
8
9
10
11
12
|
import static java.time.temporal.TemporalAdjusters.*;
... // last day of 2014 (2014-12-31) LocalDate lastDayOfYear = date.with(lastDayOfYear()); // first day of next month (2014-03-01) LocalDate firstDayOfNextMonth = date.with(firstDayOfNextMonth()); // next sunday (2014-03-02) LocalDate nextSunday = date.with(next(DayOfWeek.SUNDAY)); |
Time zones
Working with time zones is another big topic that is simplified by the new API. The LocalDate/Time classes we have seen so far do not contain information about a time zone. If we want to work with a date/time in a certain time zone we can use ZonedDateTime or OffsetDateTime:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
ZoneId losAngeles = ZoneId.of( "America/Los_Angeles" );
ZoneId berlin = ZoneId.of( "Europe/Berlin" );
// 2014-02-20 12:00 LocalDateTime dateTime = LocalDateTime.of( 2014 , 02 , 20 , 12 , 0 );
// 2014-02-20 12:00, Europe/Berlin (+01:00) ZonedDateTime berlinDateTime = ZonedDateTime.of(dateTime, berlin); // 2014-02-20 03:00, America/Los_Angeles (-08:00) ZonedDateTime losAngelesDateTime = berlinDateTime.withZoneSameInstant(losAngeles); int offsetInSeconds = losAngelesDateTime.getOffset().getTotalSeconds(); // -28800
// a collection of all available zones Set<String> allZoneIds = ZoneId.getAvailableZoneIds(); // using offsets LocalDateTime date = LocalDateTime.of( 2013 , Month.JULY, 20 , 3 , 30 );
ZoneOffset offset = ZoneOffset.of( "+05:00" );
// 2013-07-20 03:30 +05:00 OffsetDateTime plusFive = OffsetDateTime.of(date, offset); // 2013-07-19 20:30 -02:00 OffsetDateTime minusTwo = plusFive.withOffsetSameInstant(ZoneOffset.ofHours(- 2 ));
|
Timestamps
Classes like LocalDate and ZonedDateTime provide a human view on time. However, often we need to work with time viewed from a machine perspective. For this we can use the Instant class which represents timestamps. An Instant counts the time beginning from the first second of January 1, 1970 (1970-01-01 00:00:00) also called the EPOCH. Instant values can be negative if they occured before the epoch. They follow ISO 8601 the standard for representing date and time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// current time Instant now = Instant.now(); // from unix timestamp, 2010-01-01 12:00:00 Instant fromUnixTimestamp = Instant.ofEpochSecond( 1262347200 );
// same time in millis Instant fromEpochMilli = Instant.ofEpochMilli(1262347200000l); // parsing from ISO 8601 Instant fromIso8601 = Instant.parse( "2010-01-01T12:00:00Z" );
// toString() returns ISO 8601 format, e.g. 2014-02-15T01:02:03Z String toIso8601 = now.toString(); // as unix timestamp long toUnixTimestamp = now.getEpochSecond();
// in millis long toEpochMillis = now.toEpochMilli();
// plus/minus methods are available too Instant nowPlusTenSeconds = now.plusSeconds( 10 );
|
Periods and Durations
Period and Duration are two other important classes. Like the names suggest they represent a quantity or amount of time. A Period uses date based values (years, months, days) while a Duration uses seconds or nanoseconds to define an amount of time. Duration is most suitable when working with Instants and machine time. Periods and Durations can contain negative values if the end point occurs before the starting point.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
// periods LocalDate firstDate = LocalDate.of( 2010 , 5 , 17 ); // 2010-05-17
LocalDate secondDate = LocalDate.of( 2015 , 3 , 7 ); // 2015-03-07
Period period = Period.between(firstDate, secondDate); int days = period.getDays(); // 18
int months = period.getMonths(); // 9
int years = period.getYears(); // 4
boolean isNegative = period.isNegative(); // false
Period twoMonthsAndFiveDays = Period.ofMonths( 2 ).plusDays( 5 );
LocalDate sixthOfJanuary = LocalDate.of( 2014 , 1 , 6 );
// add two months and five days to 2014-01-06, result is 2014-03-11 LocalDate eleventhOfMarch = sixthOfJanuary.plus(twoMonthsAndFiveDays); // durations Instant firstInstant= Instant.ofEpochSecond( 1294881180 ); // 2011-01-13 01:13
Instant secondInstant = Instant.ofEpochSecond( 1294708260 ); // 2011-01-11 01:11
Duration between = Duration.between(firstInstant, secondInstant); // negative because firstInstant is after secondInstant (-172920) long seconds = between.getSeconds();
// get absolute result in minutes (2882) long absoluteResult = between.abs().toMinutes();
// two hours in seconds (7200) long twoHoursInSeconds = Duration.ofHours( 2 ).getSeconds();
|
Formatting and parsing
Formatting and parsing is another big topic when working with dates and times. In Java 8 this can be accomplished by using the format() and parse() methods:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
// 2014-04-01 10:45 LocalDateTime dateTime = LocalDateTime.of( 2014 , Month.APRIL, 1 , 10 , 45 );
// format as basic ISO date format (20140220) String asBasicIsoDate = dateTime.format(DateTimeFormatter.BASIC_ISO_DATE); // format as ISO week date (2014-W08-4) String asIsoWeekDate = dateTime.format(DateTimeFormatter.ISO_WEEK_DATE); // format ISO date time (2014-02-20T20:04:05.867) String asIsoDateTime = dateTime.format(DateTimeFormatter.ISO_DATE_TIME); // using a custom pattern (01/04/2014) String asCustomPattern = dateTime.format(DateTimeFormatter.ofPattern( "dd/MM/yyyy" ));
// french date formatting (1. avril 2014) String frenchDate = dateTime.format(DateTimeFormatter.ofPattern( "d. MMMM yyyy" , new Locale( "fr" )));
// using short german date/time formatting (01.04.14 10:45) DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) .withLocale( new Locale( "de" ));
String germanDateTime = dateTime.format(formatter); // parsing date strings LocalDate fromIsoDate = LocalDate.parse( "2014-01-20" );
LocalDate fromIsoWeekDate = LocalDate.parse( "2014-W14-2" , DateTimeFormatter.ISO_WEEK_DATE);
LocalDate fromCustomPattern = LocalDate.parse( "20.01.2014" , DateTimeFormatter.ofPattern( "dd.MM.yyyy" ));
|
Conversion between different date / time objects
Of course we do not always have objects of the type we need. Therefore, we need an option to convert different date/time related objects between each other. The following examples show some of the possible conversion options:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// LocalDate/LocalTime <-> LocalDateTime LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTimeFromDateAndTime = LocalDateTime.of(date, time); LocalDate dateFromDateTime = LocalDateTime.now().toLocalDate(); LocalTime timeFromDateTime = LocalDateTime.now().toLocalTime(); // Instant <-> LocalDateTime Instant instant = Instant.now(); LocalDateTime dateTimeFromInstant = LocalDateTime.ofInstant(instant, ZoneId.of( "America/Los_Angeles" ));
Instant instantFromDateTime = LocalDateTime.now().toInstant(ZoneOffset.ofHours(- 2 ));
// convert old date/calendar/timezone classes Instant instantFromDate = new Date().toInstant();
Instant instantFromCalendar = Calendar.getInstance().toInstant(); ZoneId zoneId = TimeZone.getDefault().toZoneId(); ZonedDateTime zonedDateTimeFromGregorianCalendar = new GregorianCalendar().toZonedDateTime();
// convert to old classes Date dateFromInstant = Date.from(Instant.now()); TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of( "America/Los_Angeles" ));
GregorianCalendar gregorianCalendar = GregorianCalendar.from(ZonedDateTime.now()); |
相关推荐
主要介绍了java8 LocalDate 使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
主要介绍了java8 LocalDate LocalDateTime等时间类用法,结合具体实例形式分析了LocalDate、LocalTime、LocalDateTime等日期时间相关类的功能与具体使用技巧,需要的朋友可以参考下
Java8 LocalDate和Date的相互转化工具类, 提供了两个方法。
主要介绍了Java中使用LocalDate根据日期来计算年龄的实现方法,需要的朋友可以参考下
主要给大家介绍了关于JDBC中如何使用Java8的日期LocalDate和LocalDateTime的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
主要介绍了Java8使用LocalDate计算实例代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
全网详解(波哥)Java8新特性(Lambda、Stream、LocalDate等)新特性 自学java的同行们应该都要学习java8的新特性,譬如:(Lambda、Stream、LocalDate等)!本人在学习java的时候看的是波哥的视频,确实讲的不错,很...
主要给大家介绍了关于mybatis如何使用Java8的日期LocalDate和LocalDateTime的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
Spring Boot 应用程序 mvn spring-boot:run打开WebApp: 去做将 MongoDB 更新到 1.7(取决于 Spring Boot Parent)——使用 Java8 LocalDate 而不是 java.util.Date 更新客户搜索以显示搜索结果
主要介绍了解决Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题,需要的朋友可以参考下
Java 8时态插件在Grails中集成了Java 8的新DateTime API(Instant,LocalDate,LocalTime等)。 该插件与Grails 2.5.x(支持JDK8的Grails的第一个版本)兼容。 提供将输入绑定到Java 8 Temporal的功能。 支持Java...
jd8,LocalDate类获取日期和改变日期,这是jdk8中新增的日期处理类,同时新增的还有java.time.LocalTime、java.time.LocalDateTime等
本资源是一些java8新的时间的api操作,包括LocalDate,LocalTime,LocalDateTime,Instant,Duration,时间格式化等等
java计算两个日期相隔的天数
虽然不全,但是常用的基本都有 ,希望能帮助大家,内容对新手来说还是比较容易理解的
但是jdbc对应操作date类型的数据和hibernate是不同的,hibernate不需要考虑date是util .date还是sql.date也不需要考虑存入的date是否存有时分秒了。
Java8中LocalDate、LocalTime、LocalDateTime的一些基本用法
LocalDate时间格式统一处理 获取当前月份长度 获取当前年份天数 格式化 LocalDate 为 String 格式化 LocalDateTime 为 String 字符串格式化为日期,字符串必须符合 yyyy-MM-dd 格式 字符串格式化为日期,字符串必须...
4.4 如何使用jdk8的新特性LocalDate和LocalDateTime 31 4.5 时间戳 32 6网络 33 Jsoup介绍: 34 Jsoup主要有以下功能: 34 Demo1:抓取校园网首页的新闻标题 35 //从目标页面下载所有图片到本地 36 7异常 45 2.Java...