Fun time operation

Fun time operation

Prior to JDK 8, Java language provides us with two classes for the operating time, they are: java.util.Date and java.util.Calendar, but in JDK 8 when the defect in order to solve some of the old time class of operation , provides several new classes for the operating time and date, which are: LocalTime, LocalDateTime, Instant, are located under java.time package.

The operating time is often seen in our daily development, for example, business data should record creation time and modification time, and displayed on the front page after these take time to format, and then such as we need to calculate the time intervals and other business data , are inseparable from the operation of the time, then how to properly and elegant use of time? This is the topic we are going to discuss.

Time basics of science

Greenwich Mean Time

Greenwich (also translated GMT) Britain is home to London's South Jiaoyuan Greenwich Observatory, which is the starting point for the world's computing time and the Earth longitude, longitude international conference was held in Washington in 1884, which adopted the agreement to pass Greenway governance Observatory longitude zero degrees longitude (ie prime meridian), as a starting point longitude on the Earth, and as a starting point to Greenwich "world time zone".

And Beijing's relations GMT

Greenwich Mean Time is defined as the time in the world, is 0:00 Zone, Beijing East eight districts. That is Greenwich Mean Time at 0:00 on the 1st, corresponds to the Beijing time is at 8:00 on the 1st.

Timestamp

It refers to the time stamp 1970-01-01 00:00:00 Greenwich Mean Time (GMT 1970-01-01 08:00:00) until now the total number of seconds.

JDK 8 times before the operation

1 acquisition time

Date date = new Date();
System.out.println(date);
Calendar calendar = Calendar.getInstance();
Date time = calendar.getTime();
System.out.println(time);

2 acquires a time stamp

long ts = new Date().getTime();
System.out.println(ts);
long ts2 = System.currentTimeMillis();
System.out.println(ts2);
long ts3 = Calendar.getInstance().getTimeInMillis();
System.out.println(ts3);

3 Formatting time

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sf.format(new Date()));  // output:2019-08-16 21:46:22

SimpleDateFormat meaning of configuration parameters, please refer to the following table information:

**字符** **含义** **示例**     y 年 yyyy-1996   M 月 MM-07   d 月中的天数 dd-02   D 年中的天数 121   E 星期几 星期四   H 小时数(0-23) HH-23   h 小时数(1-12) hh-11   m 分钟数 mm-02   s 秒数 ss-03   Z 时区 +0800    

Example of use:

  • Get the week: new SimpleDateFormat ( "E") format (new Date ()).
  • Get the current time zone: new SimpleDateFormat ( "Z") format (new Date * ()).

Note : In a multi-threaded under SimpleDateFormat is not thread-safe, so when you use SimpleDateFormat to pay attention to this issue. In a multi-threaded, if used improperly, could cause the results or not memory leaks and other issues.

4 Time Conversion

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// String 转 Date
String str = "2019-10-10 10:10:10";
System.out.println(sf.parse(str));
//时间戳的字符串 转 Date
String tsString = "1556788591462";
// import java.sql
Timestamp ts = new Timestamp(Long.parseLong(tsString)); // 时间戳的字符串转 Date
System.out.println(sf.format(ts));

Note : When using SimpleDateFormat.parse () method for a conversion, SimpleDateFormat constructor must be converted and consistent format string.

5 get time yesterday at the moment

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
System.out.println(calendar.getTime());

JDK 8 operating time

JDK 8 operation time added three categories: LocalDateTime, LocalDate, LocalTime.

  • LocalDate only contains the date, time does not include, immutable class, and thread-safe.
  • LocalTime contains only time, no date, immutable class, and thread-safe.
  • LocalDateTime contains both a time and includes the date, immutable class, and thread-safe.

Thread safety

It is worth mentioning that the new JDK 8 in the three time-related classes are thread-safe, which greatly reduces the risk of the next multi-threaded code development.

1 acquisition time

// 获取日期
LocalDate localDate = LocalDate.now();
System.out.println(localDate);    // output:2019-08-16
// 获取时间
LocalTime localTime = LocalTime.now();
System.out.println(localTime);    // output:21:09:13.708
// 获取日期和时间
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);    // output:2019-08-16T21:09:13.708

2 acquires a time stamp

long milli = Instant.now().toEpochMilli(); // 获取当前时间戳(精确到毫秒)
long second = Instant.now().getEpochSecond(); // 获取当前时间戳(精确到秒)
System.out.println(milli);  // output:1565932435792
System.out.println(second); // output:1565932435

3 Time Format

// 时间格式化①
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timeFormat = dateTimeFormatter.format(LocalDateTime.now());
System.out.println(timeFormat);  // output:2019-08-16 21:15:43
// 时间格式化②
String timeFormat2 = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(timeFormat2);    // output:2019-08-16 21:17:48

4 Time Conversion

String timeStr = "2019-10-10 06:06:06";
LocalDateTime dateTime = LocalDateTime.parse(timeStr,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(dateTime);

5 get time yesterday at the moment

LocalDateTime today = LocalDateTime.now();
LocalDateTime yesterday = today.plusDays(-1);
System.out.println(yesterday);

Related interview questions

1. There are several ways to get the current time?

A: Get the current time there are three common ways:

  • new Date()
  • Calendar.getInstance().getTime()
  • LocalDateTime.now()

2. How do you get at the moment of time yesterday?

A: The following are two ways to get time yesterday at the moment:

// 获取昨天此刻的时间(JDK 8 以前)
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE,-1);
System.out.println(c.getTime());
// 获取昨天此刻的时间(JDK 8)
LocalDateTime todayTime = LocalDateTime.now();
System.out.println(todayTime.plusDays(-1));

3. How to get the last day of the month?

A: The following are two ways to get the last day of this month:

// 获取本月的最后一天(JDK 8 以前)
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(ca.getTime());
// 获取本月的最后一天(JDK 8)
LocalDate today = LocalDate.now();
System.out.println(today.with(TemporalAdjusters.lastDayOfMonth()));

4. Get the current time timestamp There are several ways?

A: The following are several ways to obtain the current time stamp:

  • System.currentTimeMillis()
  • new Date().getTime()
  • Calendar.getInstance().getTime().getTime()
  • Instant.now().toEpochMilli()
  • LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()

Among them, the fourth and fifth way is JDK 8 was newly added.

5. How to calculate time separated by two time gracefully?

A: JDK 8 Duration class can be used to calculate the two time separated by the time gracefully, as follows:

LocalDateTime dt1 = LocalDateTime.now();
LocalDateTime dt2 = dt1.plusSeconds(60);
Duration duration = Duration.between(dt1, dt2);
System.out.println(duration.getSeconds());  // output:60

6. How to calculate the date of the two dates separated by gracefully?

A: JDK 8 in Period class to be used to calculate an elegant two dates spaced dates, as follows:

LocalDate d1 = LocalDate.now();
LocalDate d2 = d1.plusDays(2);
Period period = Period.between(d1, d2);
System.out.println(period.getDays());   //output:2

7. SimpleDateFormat is thread safe? why?

A: SimpleDateFormat is not thread safe. Because SimpleDateFormat view the source code can be learned, all the formatting and parsing, need to be converted via an intermediate object, the object is the intermediate Calendar, so would cause non-thread-safe. Imagine the time when we have multiple threads operate on the same data later Calendar will cover the first thread to thread, that last fact was later returned data thread, so SimpleDateFormat became a non-threaded.

8. how to ensure the thread safety of SimpleDateFormat?

A: SimpleDateFormat guarantee thread-safe as follows:

  • Synchronized use, packaged using keywords Synchronized formatting operation takes time, to ensure that the thread blocked format;
  • Manual lock, the time required to format code, written locking part, relatively Synchronized, the lower the coding efficiency, slightly better performance, higher risk of code (do not forget the risk that final, manually release the lock in operation) ;
  • JDK DateTimeFormatter 8 using alternative SimpleDateFormat.

9. JDK 8 in the new class of time what are the advantages?

A: JDK 8 advantages in particular has the following advantages, as follows:

  • Thread safety
  • Ease of use (such as access to the convenience of the current timestamp, increase or decrease the convenience of date, etc.)
  • More coding a simple and elegant format as the current time: LocalDateTime.now () format (DateTimeFormatter.ofPattern ( "yyyy-MM-dd HH: mm: ss")).;

10. How comparing two time (Date) of?

A: The time comparing the following three ways:

  • Obtaining two time stamp, to give two types of variables long, subtracting two variables, it is determined by the size of positive and negative results;
  • By Date comes before (), after (), equals () methods such comparison, sample code date1.before (date2);
  • Comparison of the compareTo method (), Code Example: date1.compareTo (date2), the return value of -1 indicates a time prior to a time smaller than the latter, is equal to 0 indicates two time before a time of greater than 1 indicates a later time.

to sum up

Before using JDK 8 java.util.Date and java.util.Calendar to the operation time, they have two very distinct disadvantages, first, the non-secure thread; second, the API call is not convenient. JDK 8 LocalDateTime added at several time-based operations java.time package, LocalDate, LocalTime, Duration (apart calculation time), Period (apart calculation date) and DateTimeFormatter, provides a multi-threaded thread safety and ease of use so that we can better operating time.
___

I welcome the attention of the public number, keyword reply " the Java ", there will be a gift both hands! ! ! I wish you a successful interview ! ! !

Guess you like

Origin www.cnblogs.com/dailyprogrammer/p/12267588.html