当前位置:网站首页>The new CTO strongly prohibits the use of calendar?
The new CTO strongly prohibits the use of calendar?
2022-07-27 21:20:00 【Hollis Chuang】
Java 8 It has been widely used , But it is still used Java Calendar Processing time and date , Not only poor performance , Very cutting code, very redundant , You can't use Java 8 What's new API Do you ? therefore CTO Forced , Must use Java 8 Processing date , Otherwise, they will be dismissed . Here's the finishing 18 A way to deal with dates , It can be collected , It must be useful .
Java Processing date 、 The calendar and time approach has long been criticized by the community , take java.util.Date Set to variable type , as well as SimpleDateFormat Non-thread-safe makes its application very limited .
new API be based on ISO Standard calendar system ,java.time All classes under the package are immutable and thread safe .

Example 1:Java 8 Get today's date
Java 8 Medium LocalDate Used to indicate the date of the day . and java.util.Date Different , It has only date , Not including time . Use this class when you just need to represent dates .
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo01 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(" Today's date :"+today);
}
}Example 2:Java 8 Get the year 、 month 、 Daily information
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo02 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.println("year:"+year);
System.out.println("month:"+month);
System.out.println("day:"+day);
}
}Example 3:Java 8 Processing specific dates
We use the static factory method now() It's very easy to create the date of the day , You can also call another useful factory method LocalDate.of() Create any date , This method needs to be introduced in 、 month 、 Daily parameters , Return the corresponding LocalDate example . The advantage of this method is that it doesn't get old again API Design mistakes , For example, the year starts from 1900, From the month 0 open First wait .
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo03 {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2018,2,6);
System.out.println(" Custom date :"+date);
}
}Example 4:Java 8 Determine whether two dates are equal
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo04 {
public static void main(String[] args) {
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018,2,5);
if(date1.equals(date2)){
System.out.println(" Time is equal ");
}else{
System.out.println(" Time is not equal ");
}
}
}Example 5:Java 8 Check for periodic events like birthdays
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.MonthDay;
public class Demo05 {
public static void main(String[] args) {
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018,2,6);
MonthDay birthday = MonthDay.of(date2.getMonth(),date2.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(date1);
if(currentMonthDay.equals(birthday)){
System.out.println(" It's your birthday ");
}else{
System.out.println(" Your birthday hasn't arrived yet ");
}
}
}As long as the date of the day matches the birthday , Congratulations will be printed no matter what year . You can integrate the program into the system clock , See if you'll be reminded on your birthday , Or write a unit test to check whether the code is running correctly .
Example 6:Java 8 Get the current time
package com.shxt.demo02;
import java.time.LocalTime;
public class Demo06 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println(" Gets the current time , No date :"+time);
}
}You can see that the current time only contains time information , No date
Example 7:Java 8 Get the current time
By adding hours 、 branch 、 Seconds to calculate the future time is common .Java 8 In addition to the benefits of immutable types and thread safety , It also provides a better plusHours() Methods to replace add(), And it's compatible . Be careful , These methods return a whole new LocalTime example , Because of its immutability , When you return, you must assign a value with a variable .
package com.shxt.demo02;
import java.time.LocalTime;
public class Demo07 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(3);
System.out.println(" The time after three hours is :"+newTime);
}
}Example 8:Java 8 How to calculate the date in a week
And the last example 3 Hours later, the time is similar to , This example calculates the date in a week .LocalDate Date does not contain time information , its plus() Method to add days 、 Zhou 、 month ,ChronoUnit Class declares these time units . because LocalDate It's the same type , When you return, you must assign a value with a variable .
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo08 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(" Today's date is :"+today);
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println(" The date a week later is :"+nextWeek);
}
}You can see that the new date is 7 God , It's a week . You can add... In the same way 1 Months 、1 year 、1 Hours 、1 Minutes or even a century , More options are available Java 8 API Medium ChronoUnit class
Example 9:Java 8 Calculate the date one year ago or one year later
utilize minus() Method calculate the date one year ago
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo09 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
System.out.println(" Date a year ago : " + previousYear);
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println(" A year later :"+nextYear);
}
}Example 10:Java 8 Of Clock Clock class
Java 8 Added one Clock The clock class is used to get the timestamp at the time , Or date time information in the current time zone . Used to use System.currentTimeInMillis() and TimeZone.getDefault() All places are available Clock Replace .
package com.shxt.demo02;
import java.time.Clock;
public class Demo10 {
public static void main(String[] args) {
// Returns the current time based on your system clock and set to UTC.
Clock clock = Clock.systemUTC();
System.out.println("Clock : " + clock.millis());
// Returns time based on system clock zone
Clock defaultClock = Clock.systemDefaultZone();
System.out.println("Clock : " + defaultClock.millis());
}
}Example 11: How to use Java Judge whether the date is earlier or later than another date
Another common operation in the work is how to judge whether a given date is greater than or less than a day ? stay Java 8 in ,LocalDate Class has two kinds of methods isBefore() and isAfter() Used to compare dates . call isBefore() When the method is used , Returns... If the given date is less than the current date true.
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo11 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate tomorrow = LocalDate.of(2018,2,6);
if(tomorrow.isAfter(today)){
System.out.println(" The date after :"+tomorrow);
}
LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
if(yesterday.isBefore(today)){
System.out.println(" Previous date :"+yesterday);
}
}
}Example 12:Java 8 Processing time zone
Java 8 It's not just a separation of date and time , Time zones are also separated . Now there are a series of separate classes like ZoneId To handle specific time zones ,ZoneDateTime Class to represent the time in a time zone . This is in Java 8 It used to be GregorianCalendar Class . The following example shows how to convert the time in this time zone to the time in another time zone .
package com.shxt.demo02;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Demo12 {
public static void main(String[] args) {
// Date and time with timezone in Java 8
ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america );
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
}
}Example 13: How to express a fixed date such as the expiration of a credit card , The answer lies in YearMonth
And MonthDay Examples of checking for repeat events are similar ,YearMonth Is another composite class , Used to indicate the expiry date of a credit card 、FD due date 、 Expiration date of futures options, etc . You can also use this class to get How many days are there in the month ,YearMonth Example of lengthOfMonth() Method returns the number of days in the current month , In judging 2 Monthly 28 Heaven is still 29 The weather is very useful .
package com.shxt.demo02;
import java.time.*;
public class Demo13 {
public static void main(String[] args) {
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
}
}Example 14: How to be in Java 8 Check leap year
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo14 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
if(today.isLeapYear()){
System.out.println("This year is Leap year");
}else {
System.out.println("2018 is not a Leap year");
}
}
}Example 15: Calculate the number of days and months between the two dates
A common date operation is to calculate the number of days between two dates 、 Weeks or months . stay Java 8 Can be used in the java.time.Period Class to do the calculation .
In the following example , We calculated the number of months between the day and the day to come .
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.Period;
public class Demo15 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate java8Release = LocalDate.of(2018, 12, 14);
Period periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : "
+ periodToNextJavaRelease.getMonths() );
}
}Example 16: stay Java 8 Get the current timestamp
Instant Class has a static factory method now() Will return the current timestamp , As shown below :
package com.shxt.demo02;
import java.time.Instant;
public class Demo16 {
public static void main(String[] args) {
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp.toEpochMilli());
}
}The time stamp information contains both date and time , This sum java.util.Date It's like . actually Instant Class is really equivalent to Java 8 Previous Date class , You can use Date Classes and Instant Class's own transformation methods transform each other , for example :Date.from(Instant) take Instant convert to java.util.Date,Date.toInstant() Will be Date Class to Instant class .
Example 17:Java 8 How to use a predefined formatting tool to parse or format dates
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Demo17 {
public static void main(String[] args) {
String dayAfterTommorrow = "20180205";
LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(dayAfterTommorrow+" The formatted date is : "+formatted);
}
}Example 18: String conversion date type
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo18 {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
// Date to string
String str = date.format(format1);
System.out.println(" Date to string :"+str);
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
// String to date
LocalDate date2 = LocalDate.parse(str,format2);
System.out.println(" The date type :"+date2);
}
} link :http://suo.im/5RJhaUEnd
My new book 《 In depth understanding of Java The core technology 》 It's on the market , After listing, it has been ranked in Jingdong best seller list for several times , At present 6 In the discount , If you want to start, don't miss it ~ Long press the QR code to buy ~

Long press to scan code and enjoy 6 A discount
Previous recommendation
One I admire very much Google bosses , quit ..
There is Tao without skill , It can be done with skill ; No way with skill , Stop at surgery
Welcome to pay attention Java Road official account

Good article , I was watching ️
边栏推荐
- 成分句法分析综述(第二版)
- Paper appreciation [aaai18] meta multi task learning for sequence modeling
- Unity installs personal free edition
- mysql 最大建议行数2000w,靠谱吗?
- How to check the Bluetooth version of Bluetooth headset
- MySQL data recovery process is based on binlog redolog undo
- LeetCode每日一练 —— 876. 链表的中间结点
- Uncaught SyntaxError: redeclaration of let page
- Dobot magician robot arm - Introduction
- Hexagon_ V65_ Programmers_ Reference_ Manual(7)
猜你喜欢
随机推荐
“地理-语言”大模型文心ERNIE-GeoL及应用
LabVIEW learning note 5: you cannot return to the original state after pressing the button
PG 之 Free Space Map & Visibility Map
LabVIEW learning note 9: capture the "value change" event generated by the program modifying the control value
Dobot Magician 机器臂-简介
新来CTO 强烈禁止使用Calendar...,那用啥?
API gateway introduction
建筑云渲染的应用正在扩大,越来越多的行业急需可视化服务
工程技术开发的圈套与局限性
The use experience of the product is up to you in the evaluation and exchange meeting of the flying oar frame experience!
Leetcode-209- subarray with the smallest length
ACM MM 2022 | 浙大提出:点云分割主动学习新SOTA
Opencv implements image clipping and scaling
飞桨框架体验评测交流会,产品的使用体验由你来决定!
Force buckle 919. Complete binary tree inserter
The maximum recommended number of rows for MySQL is 2000W. Is it reliable?
QT OpenGL makes objects move under care to form animation
mysql 最大建议行数2000w,靠谱吗?
Pytest失败重跑
中英文说明书丨 AbFluor 488 细胞凋亡检测试剂盒











![论文赏析[AAAI18]面向序列建模的元多任务学习](/img/2b/345b5a287fcd9c9b1a86ae683f124b.png)
