In the project development process often encountered in processing time, but do you really use it right, please, understand Alibaba Developer's Handbook disable static modification SimpleDateFormat it
By reading this article you'll learn:
- Why
LocalDate
, ,LocalTime
[java8LocalDateTime
new offer classes] java8
The new timeAPI
use, including creating, formatting, parsing, calculate, modify
Why LocalDate, LocalTime, LocalDateTime
-
Date
If you do not format, print out the poor readability of dateTue Sep 10 09:34:04 CST 2019 复制代码
-
Use
SimpleDateFormat
time format, butSimpleDateFormat
is thread safeSimpleDateFormat
theformat
method for final calling code:private StringBuffer format(Date date, StringBuffer toAppendTo, FieldDelegate delegate) { // Convert input date to time field list calendar.setTime(date); boolean useDateFormatSymbols = useDateFormatSymbols(); for (int i = 0; i < compiledPattern.length; ) { int tag = compiledPattern[i] >>> 8; int count = compiledPattern[i++] & 0xff; if (count == 255) { count = compiledPattern[i++] << 16; count |= compiledPattern[i++]; } switch (tag) { case TAG_QUOTE_ASCII_CHAR: toAppendTo.append((char)count); break; case TAG_QUOTE_CHARS: toAppendTo.append(compiledPattern, i, count); i += count; break; default: subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols); break; } } return toAppendTo; } 复制代码
calendar
It is a shared variable, and this shared variables do not thread-safe control. When multiple threads simultaneously using the sameSimpleDateFormat
objects [such as astatic
modifiedSimpleDateFormat
] callsformat
upon the method, multiple threads can simultaneously callcalendar.setTime
method, a thread may have just set thetime
value of another thread immediately set thetime
value to modify the format of the result in the return of of time may be wrong. In the case of the use of multiple concurrentSimpleDateFormat
need extra attentionSimpleDateFormat
in addition toformat
outside are thread-unsafeparse
methods are thread safe.parse
The actual method calls thealb.establish(calendar).getTime()
method to resolve,alb.establish(calendar)
the method was mainly finished-
- Cal property values of target replacement date
-
- Using the attributes provided cal calb
-
- Back Set a good cal objects
-
But this is not a three-step atomic operation
How to ensure that multi-threaded thread-safe - Avoid sharing a thread between SimpleDateFormat
objects are created once each thread uses SimpleDateFormat
the object => large overhead of creating and destroying objects - use format
and parse
local methods for locking => poor blocking performance thread - use ThreadLocal
to ensure that each thread created only once at most SimpleDateFormat
objects => better way
Date
Time is too much trouble to deal with, such as want to get a year, a month, a week, andn
after days, ifDate
to deal with the case so hard, you might sayDate
class is not theregetYear
,getMonth
these methods do, get date veryEasy
, but they have been abandoned ah
Use java8 new date and time API together Come On
LocalDate
The date will only get
-
create
LocalDate
//获取当前年月日 LocalDate localDate = LocalDate.now(); //构造指定的年月日 LocalDate localDate1 = LocalDate.of(2019, 9, 10); 复制代码
-
Get year, month, date, day of the week
int year = localDate.getYear(); int year1 = localDate.get(ChronoField.YEAR); Month month = localDate.getMonth(); int month1 = localDate.get(ChronoField.MONTH_OF_YEAR); int day = localDate.getDayOfMonth(); int day1 = localDate.get(ChronoField.DAY_OF_MONTH); DayOfWeek dayOfWeek = localDate.getDayOfWeek(); int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK); 复制代码
LocalTime
You will only get a few minutes and seconds
-
create
LocalTime
LocalTime localTime = LocalTime.of(13, 51, 10); LocalTime localTime1 = LocalTime.now(); 复制代码
-
Get minutes and seconds
//获取小时 int hour = localTime.getHour(); int hour1 = localTime.get(ChronoField.HOUR_OF_DAY); //获取分 int minute = localTime.getMinute(); int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR); //获取秒 int second = localTime.getMinute(); int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE); 复制代码
localdateti to
When the acquisition date, day, hour, equal to LocalDate + LocalTime
-
create
LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56); LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime); LocalDateTime localDateTime3 = localDate.atTime(localTime); LocalDateTime localDateTime4 = localTime.atDate(localDate); 复制代码
-
Obtain
LocalDate
LocalDate localDate2 = localDateTime.toLocalDate(); 复制代码
-
Obtain
LocalTime
LocalTime localTime2 = localDateTime.toLocalTime(); 复制代码
Instant
Gets the number of seconds
-
Creating
Instant
ObjectsInstant instant = Instant.now(); 复制代码
-
Gets the number of seconds
long currentSecond = instant.getEpochSecond(); 复制代码
-
Gets the number of milliseconds
long currentMilli = instant.toEpochMilli(); 复制代码
Personally I feel that if only to get the number of seconds or milliseconds, use System.currentTimeMillis()
is much more convenient
修改 LOCALDATE, localtime, localdateti to Instant
LocalDate
, LocalTime
, LocalDateTime
, Instant
As immutable objects , to modify these objects objects will return a copy of the
- Increase, decrease the number of years, months, days, etc. in order to
LocalDateTime
, for exampleLocalDateTime localDateTime = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56); //增加一年 localDateTime = localDateTime.plusYears(1); localDateTime = localDateTime.plus(1, ChronoUnit.YEARS); //减少一个月 localDateTime = localDateTime.minusMonths(1); localDateTime = localDateTime.minus(1, ChronoUnit.MONTHS); 复制代码
- By
with
modifying certain values//修改年为2019 localDateTime = localDateTime.withYear(2020); //修改为2022 localDateTime = localDateTime.with(ChronoField.YEAR, 2022); 复制代码
You can also modify the month, day
Time calculation
For example, some want to know when the last day of this month is the date, next weekend is the date, you can quickly get an answer by providing time and date API
LocalDate localDate = LocalDate.now();
LocalDate localDate1 = localDate.with(firstDayOfYear());
复制代码
Such as by firstDayOfYear()
return to the current date of the first day of the date, there are many ways not illustrated here
Formatting time
LocalDate localDate = LocalDate.of(2019, 9, 10);
String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
//自定义格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String s3 = localDate.format(dateTimeFormatter);
复制代码
DateTimeFormatter
The default format offers a variety of ways, if not meet the requirements provided by default, through DateTimeFormatter
the ofPattern
way to create a custom format mode
Resolution Time
LocalDate localDate1 = LocalDate.parse("20190910", DateTimeFormatter.BASIC_ISO_DATE);
LocalDate localDate2 = LocalDate.parse("2019-09-10", DateTimeFormatter.ISO_LOCAL_DATE);
复制代码
And SimpleDateFormat
compared, DateTimeFormatter
are thread-safe
summary
LocalDateTime
: Date
Some I have, Date
no I have, please select the datePick Me