Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use date and time API technology in the basics of Java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to use date and time API technology in the basic article of Java". In daily operation, I believe that many people have doubts about how to use date and time API technology in the basic article of Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to use date and time API technology in the basic article of Java". Next, please follow the editor to study!

I. time and date

In system development, date and time, as important business factors, play a key role, such as data generation under the same time node, statistics and analysis of all kinds of data based on time range, cluster node uniform time to avoid timeout and so on.

There are several key concepts in time and date:

Date: usually the combination of year, month and day represents the current date.

Time: usually the combination of hours, minutes and seconds represents the current time.

Time zone: the longitude of different countries and regions in the world is different, divided into 24 standard time zones, the time difference between adjacent time zones is one hour.

Timestamp: the total number of seconds from 1970-1-1 00:00:00 UTC time to now.

The use of date and time in the system is usually to obtain time and some common calculation and format conversion processing, which will become much more complex in some collapsed time zone business, such as global trade or Haitao in e-commerce business.

II. JDK native API1, Date foundation

Basic usage

Java.sql.Date inherits java.util.Date, and most of the related methods call parent methods directly.

Public class DateTime01 {public static void main (String [] args) {long nowTime = System.currentTimeMillis (); java.util.Date data01 = new java.util.Date (nowTime); java.sql.Date date02 = new java.sql.Date (nowTime); System.out.println (data01); System.out.println (date02.getTime ());} print: Fri Jan 29 15:11:25 CST 20211611904285848

Calculation rule

Public class DateTime02 {public static void main (String [] args) {Date nowDate = new Date (); System.out.println ("year:" + nowDate.getYear ()); System.out.println ("month:" + nowDate.getMonth ()); System.out.println ("Day:" + nowDate.getDay ());}}

Year: current time minus 1900

Public int getYear () {return normalize () .getYear ()-1900;}

Month: 0-11 means January-December

Public int getMonth () {return normalize () .getMonth ()-1;}

Talent: normal expression

Public int getDay () {return normalize () .getDayOfWeek ()-BaseCalendar.SUNDAY;}

Format conversion

Non-thread safe date conversion API, which is not allowed in the development of the specification.

Public class DateTime02 {public static void main (String [] args) throws Exception {/ / default conversion DateFormat dateFormat01 = new SimpleDateFormat (); String nowDate01= dateFormat01.format (new Date ()); System.out.println ("nowDate01=" + nowDate01); / / specify format conversion String format = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat dateFormat02 = new SimpleDateFormat (format) String nowDate02= dateFormat02.format (new Date ()); System.out.println ("nowDate02=" + nowDate02); / / parsing time String parse = "yyyy-MM-dd HH:mm"; SimpleDateFormat dateFormat03 = new SimpleDateFormat (parse); Date parseDate= dateFormat03.parse ("2021-01-18 16:59:59"); System.out.println ("parseDate=" + parseDate);}}

As the date and time used since the initial version of JDK, the Date class has always been used in the project, but the related API methods have been largely abandoned, usually using some re-encapsulated time components. The design of the API is the worst in Java.

2. Calendar upgrade

As an abstract class, Calendar defines the method of date-time-dependent transformation and calculation. This class is visual.

Public class DateTime04 {public static void main (String [] args) {Calendar calendar = Calendar.getInstance (); calendar.set (Calendar.YEAR,2021); calendar.set (Calendar.MONTH,1); calendar.set (Calendar.DAY_OF_MONTH,12); calendar.set (Calendar.HOUR_OF_DAY,23); calendar.set (Calendar.MINUTE,59); calendar.set (Calendar.SECOND,59) Calendar.set (Calendar.MILLISECOND,0); DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); Date defDate = calendar.getTime (); System.out.println (defDate+ "| |" + dateFormat.format (defDate));}} output: Fri Feb 12 23:59:59 CST 2021 | | 2021-02-12 23:59:59 |

Intuitively, the related methods in Date migrate the implementation of Calendar, the function of simplified Date focuses on the entity encapsulation of date and time, Calendar complex related computing strategy, DateFormat is still used for format processing. But Calendar is still rarely used, and the above basic API is a good illustration.

3. JDK1.8 upgrade API

In versions after Java8, the core API classes include LocalDate- date, LocalTime- time, and LocalDateTime- date plus time.

LocalDate: date description is an immutable class decorated with final. The default format is yyyy-MM-dd.

LocalTime: time description is an immutable class decorated with final. The default format is hh:mm:ss.zzz.

LocalDateTime: an immutable class that describes the final decoration of the date and time.

Public class DateTime05 {public static void main (String [] args) {/ / date: year-month-day System.out.println (LocalDate.now ()); / / time: hour-minute-second-millisecond System.out.println (LocalTime.now ()); / / date time: year-month-day-minute-second-millisecond System.out.println (LocalDateTime.now ()) / / date node gets LocalDate localDate = LocalDate.now (); System.out.println ("[" + localDate.getYear () + "year] ["+ localDate.getMonthValue () +" month] ["+ localDate.getDayOfMonth () +" day]); / / calculation method System.out.println ("1 year later:" + localDate.plusYears (1)); System.out.println ("before February:" + localDate.minusMonths (2)); System.out.println ("3 weeks later:" + localDate.plusWeeks (3)); System.out.println ("3 days ago:" + localDate.minusDays (3)) / time comparison LocalTime localTime1 = LocalTime.of (12,45,45); LocalTime localTime2 = LocalTime.of (16,30,30); System.out.println (localTime1.isAfter (localTime2)); System.out.println (localTime2.isAfter (localTime1)); System.out.println (localTime2.equals (localTime1)) / date and time format LocalDateTime localDateTime = LocalDateTime.now (); LocalDate myLocalDate = localDateTime.toLocalDate (); LocalTime myLocalTime = localDateTime.toLocalTime (); System.out.println ("date:" + myLocalDate); System.out.println ("time:" + myLocalTime);}}

If you are a deep user of JodaTime components, there is little pressure to use these API.

4. Time stamp

Timestamps are also commonly used in business. Time is represented based on the Long type, which is much better than the regular date and time format in many cases.

Public class DateTime06 {public static void main (String [] args) {/ / accurate to millisecond System.out.println (System.currentTimeMillis ()); System.out.println (new Date (). GetTime ()); System.out.println (Calendar.getInstance (). GetTime (). GetTime ()) System.out.println (LocalDateTime.now () .toInstant (ZoneOffset.of ("+ 8")) .toEpochMilli ();}}

It should be noted that in the actual business, there are various ways to obtain timestamps, so it is recommended to unify the tool method and specify the accuracy, so as to avoid the problem of partial accuracy to seconds and partial accuracy to milliseconds. In this way, the conversion between them can be avoided.

III. JodaTime components

Before Java8, JodaTime components are a common choice in most systems, and there are many convenient date and time processing methods to encapsulate.

Basic dependency:

Joda-time joda-time

Make a simple tool class encapsulation on top of the components provided by joda-time to ensure a unified business processing style.

Public class JodaTimeUtil {/ / time format public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private JodaTimeUtil () {} / / get the current time public static DateTime getCurrentTime () {return new DateTime ();} / / get the specified time public static DateTime getDateTime (Object obj) {return new DateTime (obj) } / / convert the time in the specified format to the string public static String getNowDate (Date date, String format) {return new DateTime (date) .toString (format);} / / get the time of the week public static String getWeek (Object date) {DateTime time = getDateTime (date); String week = null Switch (time.getDayOfWeek ()) {case DateTimeConstants.SUNDAY: week = "Sunday"; break; case DateTimeConstants.MONDAY: week = "Monday"; break; case DateTimeConstants.TUESDAY: week = "Tuesday"; break Case DateTimeConstants.WEDNESDAY: week = "Wednesday"; break; case DateTimeConstants.THURSDAY: week = "Thursday"; break; case DateTimeConstants.FRIDAY: week = "Friday"; break Case DateTimeConstants.SATURDAY: week = "Saturday"; break; default: break;} return week Fourth, source code address GitHub address https://github.com/cicadasmile/java-base-parentGitEE address https://gitee.com/cicadasmile/java-base-parent, on the "Java basic article on how to use date and time API technology" study is over, I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report