This article has participated in the weekend study program, click to see the details

Java has these time manipulation classes:

When JDK8 is released, three time processing classes LocalDate, LocalTime, and LocalDateTime are introduced

Date

Prior to JDK 1.1, Date had two additional features. It allows the date to be interpreted as year, month, day, hour, minute, and a second value. It also allows formatting and parsing of date strings. Unfortunately, the APIS for these functions are not suitable for internationalization. As of JDK 1.1, the Calendar class should be used to convert between date and time fields, and the DateFormat class should be used to format and parse date strings. The corresponding method Date is deprecated.

Although the Date class is intended to reflect coordinated world Time (UTC), it may not do so depending on the host environment of the Java virtual Machine. Almost all modern operating systems assume that in all cases 1 day = 24×60×60 = 86,400 seconds. In UTC, however, a second, called a “leap second,” occurs every year or two. A leap second is always the last second of the day, always on December 31 or June 30. In 1995, for example, the last minute was 61 seconds, thanks to the addition of leap seconds. Most computer clocks are not accurate enough to reflect the difference between leap seconds.

Some computer standards are defined in terms of Greenwich Mean Time (GMT), equivalent to universal time (UT). GMT is the standard “civil” name; UT is the same standard “scientific” name. The difference between UTC and UT is that UTC is based on atomic clocks and UT is based on astronomical observations, which for all practical purposes is an invisible fuffle. Because the Earth rotates inuniformly (slowing down and accelerating in complicated ways), UT does not always flow uniformly. As needed, the time difference is introduced into UTC so that UT remains UTC for 0.9 seconds of UT1, which is the version of UT, with some modifications applied. There are other time and date systems; The satellite-based Global Positioning System (GPS), for example, uses a time scale that synchronizes with UTC but does not adjust for leap seconds. An interesting source of further information is the U.S. Naval Observatory, specifically the Time Bureau at:

Date d1 = new Date(); Log.info (" current time: "+d1); Log.info (" time in milliseconds: "+ System.currentTimemillis ()); //y represents the year //M represents the month //d represents the day //H represents the hour in 24 //H represents the hour in 12 //M represents the minute //s represents the second //s represents the millisecond SimpleDateFormat SDF =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS" ); String format = sdf.format(d1); Log.info (" after formatting :"+format); Date(int year, int month, int day); Date(int year, int month, int day); Date(int year, int month, int day) // The actual month to represent is subtracted from 1. Date d2 = new Date(2020-1900, 6-1, 12); // Log.info (" specify time: "+d2) is not recommended if it is obsolete; Int year = d2.getYear() + 1900; int year = d2.getYear() + 1900; Log.info (" year: "+year); Int month = d2.getmonth () + 1; // Log.info (" month: "+month) is not recommended if it is obsolete; Int date = d2.getDate(); Log.info (" date: "+month); Int hour = d2.gethours (); // Do not set the default to 0. Log.info (" hour: "+hour); Int minute = d2.getminutes (); // Log.info (" minute: "+minute) is not recommended if it is obsolete; Int second = d2.getseconds (); // Log.info (" second: "+second) is not recommended if it is obsolete; Int day = d2.getDay(); int day = d2.getDay(); // Log.info (" week: "+day) is not recommended;Copy the code

Java. Util. Date, Java, SQL Date difference

Date: Date: Date: Date: Date: Date: Date: Date: Date: Date: Date: Date: Date: Date The setDate() argument for PreparedStament and the getDate() method for ResultSet are java.sql.date. Java.util. Date is the parent class of java.sql.Date. Java.lang. Object — “java.util.Date –” java.sql.Date 4. The usage rate of java.sql

Calendar

The Calendar class is an abstract class that can be used to convert methods such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on between a particular time and a group of Calendar fields, as well as to manipulate the Calendar field such as to get the date of the next week. An instant in time can be expressed as a millisecond value. This value is the offset from the Epoch of January 1, 1970 at 00:00 00:00.000 GMT (Gregorian)

@Slf4j public class Calendardome { public static void main(String[] args) { SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss HHH" ); Calendar1 = Calendar.getInstance(); Log.info (" current time: "+calendar1); Log.info (" after formatting :"+sdf.format(calendar1.gettime ())); Calendar2 = New GregorianCalendar(2016, 8, 1, 15, 41, 22); Log.info (" specify time: "+calendar2); Log.info (" after formatting :"+sdf.format(calendar2.gettime ())); Int year = Calendar 2. Get (Calendar. Year); The info (" : "+ year); Int Calendar = calendar2.get(calendar.month) + 1; Log.info (" month: "+month); Int Calendar = calendar2.get(calendar.day_of_month); Day log. The info (" : "+ day); Int hover = calendar2.get(calendar.hour_of_day); The info (" : "+ hover); Int minute = Calendar 2. Get (calendar.minute); Log.info (" minute: "+minute); Int seconds = calendar2.get(Calendar.second); The info (" seconds: "+ seconds); Int week = calendar2. Get (Calendar.DAY_OF_WEEK); Log.info (" week: "+week); String timeDeffer = getTimeDeffer(sdf.format(calendar1.getTime()), sdf.format(calendar2.getTime())); log.info(timeDeffer); } public static String getTimeDeffer(String time1,String); /** 2 * getTimeDeffer(String time1,String) time2) { String result = ""; if(StringUtils.isNotBlank(time1)&& StringUtils.isNotBlank(time2)){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { long dt1 = sdf.parse( time1 ).getTime(); long dt2 = sdf.parse( time2 ).getTime(); long dc = Math.abs(dt2-dt1); long seconds = dc/1000; long date = seconds/(24*60*60); Long hour = (seconds-date*24*60*60)/(60*60); Long minut = (seconds-date*24*60*60-hour*60*60)/(60); Long second = (seconds-date*24*60*60-hour*60*60-minut*60); Return (date==0?") ": (date + the" day ")) + (hour = = 0?" "(hour +" hour ")) + (minut = = 0?" "(minut +" ")) + (second = = 0?" "(the second +" seconds ")); } catch ( ParseException e) { e.printStackTrace(); } } return result; }}Copy the code

LocalDate, LocalTime and LocalDateTime

Why does JDK8 introduce LocalDate, LocalTime, and LocalDateTime?

In order to make up for the insufficiency of the previous date and time class, simplify the operation of date and time. Prior to Java8, the classes that handled Date and time were Date and Calendar, which were always uncomfortable to use, had some design flaws, and were not thread-safe.

To understand these classes in detail, we need to know a little bit about time and time zone division. In 1884, the International Longitude Conference divided the earth’s surface into 24 zones equal to the longitude line, called time zones. In other words, the zero time zone is defined as 7.5 degrees east and west longitude based on the prime meridian, and the time zone is defined as 15 degrees apart, with one hour difference between each time zone. Beijing time zone is east 8, 8 hours earlier than zero time zone. If it’s 10 o ‘clock in the zero hour zone, it’s 18 o ‘clock in Beijing time.

The Coordinated Universal Time (UTC) we usually see in the program is the Time in the zero Time zone, and its full name is Coordinated Universal Time (UTC). Another common abbreviation is Greenwich Mean Time (GMT). Greenwich mean time is in the zero hour zone, so UTC time and GMT time are the same in value.

There may be some questions, the same is on the earth ah, different regions of the time is not the same? Could I take a plane from Beijing to Greenwich and go back in time? Wouldn’t that be amazing? Haha, of course that’s not the truth. The passage of time, the aging of cells, is the same for the whole planet, so that no matter where you are on the planet, this second is gone and is gone, and it is the most fair, not one more or less of you. How do you keep track of the minutes that pass? There is a noun, called the time stamp, it refers to the total number of seconds since Greenwich time (Earth zero time zone) 1970 January 01 00 00 00 00 seconds (Beijing time January 01 1970 08 00 00 seconds), this time stamp, is consistent across the earth. Prior to 1970, there were other ways of timing, and the lack of uniformity caused some software to run at different times, which nearly led to industry disasters (specific events can be searched online). It is unrealistic to rely solely on this timestamp as a standard for people to measure time, because it has no meaning for human production and life. For example: it’s normal for us to start school at 8 a.m., but it’s not normal for us to start school at 8 a.m. At this time, time zones are divided according to the different latitude and longitude on the earth and the characteristics of the earth’s rotation. The time stamps are converted into local time according to the different time zones, which is used as the standard for working and rest, so as to facilitate people’s production and life. We can see the sun rise at 8 o ‘clock Beijing time, and they can see the sun rise at 8 o ‘clock London time.

As it turns out, timestamps are the same everywhere on earth, and if we want to convert timestamps to local time, we need to convert them according to the local time zone. The same is true for time conversion between different time zones. We need to convert the local time according to the differences in time zones

@slf4j public class LocalTimedome {public static void main(String[] args) {// Get the date of the current time zone LocalDate LocalDate = LocalDate.now(); log.info("localDate: " + localDate); LocalTime LocalTime = localtime.now (); log.info("localTime: " + localTime); LocalDateTime LocalDateTime = localDatetime. of(localDate,localTime); log.info("localDateTime: " + localDateTime); LocalDateTime localDateTime2 = localDatetime.now (); log.info("localDateTime2: " + localDateTime2); . / / formatting time DateTimeFormatter formatter = DateTimeFormatter ofPattern (" MM - dd YYYY - HH: MM: ss "); Log.info (" time after formatting: "+ localDateTime2.format(formatter)); / / into a timestamp (in seconds) long epochSecond = localDateTime2. ToEpochSecond (ZoneOffset. Of (" + 8 ")); Long epochMilli = localDateTime2.atzone (zoneoffset.systemDefault ()).toinstant ().toepochmilli (); long epochMilli = localDateTime2.atZone(zoneoffset.systemDefault ()).toepochmilli (); Log.info (" timestamp is (s) "+ epochSecond + "; "+ epochMilli); LocalDateTime = Instant. OfEpochMilli (epochMilli); LocalDateTime localDateTime3 = LocalDateTime.ofInstant(instant, ZoneOffset.systemDefault()); Log.info (" LocalDateTime: "+ localDateTime3.format(formatter)); // LocalDateTime = Instant. OfEpochSecond (epochSecond); LocalDateTime localDateTime4 = LocalDateTime.ofInstant(instant2, ZoneOffset.systemDefault()); Log.info (" LocalDateTime: "+ localDateTime4.format(formatter)); }}Copy the code

The three new classes correspond to the date-time types in MySQL. If we use a MySQL database, we do not need to do any conversion when inserting the corresponding fields. The mapping is as follows:

  • The corresponding time LocalTime
  • LocalDate corresponds to the date
  • LocalDateTime corresponding datetime (timestamp)

Time Zone (Zone)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS ", Locale.US); Calendar cd = Calendar.getInstance(); SetTimeZone (timezone.gettimezone ("GMT")); // set the TimeZone to GMT sdf.settimezone (timezone.gettimezone ("GMT")); String str = sdf.format(cd.getTime()); Log.info (" Greenwich Mean time: "+ STR); Calendar cd2 = Calendar.getInstance(); SetTimeZone (timezone.gettimezone ("GMT+8")); // set the TimeZone to GMT sdf.settimezone (timezone.gettimezone ("GMT+8")); String str2 = sdf.format(cd2.getTime()); Log.info (" Beijing time: "+str2); / / / / output all the time zone Set < String > Set = ZoneId. GetAvailableZoneIds (); //set.forEach(System.out::println); LocalDateTime dateTime = LocalDateTime.now(); dateTime.atZone(ZoneId.of("Asia/Shanghai")); Log.info (" SST :"+dateTime); Log.info (" localdatetime.now (zoneid.of ("Asia/Shanghai"))); Log.info (" New York :"+ localDatetime.now (zoneid.of ("America/New_York"))); Log.info (" London :"+ localDatetime.now (zoneid.of ("Europe/London"))); Log.info (" Shanghai, China time ":"+ zonedDatetime.now (zoneid.of ("Asia/Shanghai"))); Log.info (" Shanghai, China time (time or date with time zone):"+ zonedDatetime.now ()); LocalDateTime LocalDateTime = localDatetime. now(zoneid.of ("Asia/Shanghai")); // LocalDateTime = localDatetime. now(zoneid.of ("Asia/Shanghai")); ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai")); Log.info (" Shanghai time (localDateTime):"+localDateTime); Log.info (" zonedDateTime ":"+zonedDateTime"); / / ZonedDateTime (time or date with a time zone) turn LocalDateTime LocalDateTime localDateTime1 = ZonedDateTime. ToLocalDateTime (); Log.info (" Shanghai Time, China (time or date with time zone):"+localDateTime1);Copy the code

Spring questions about receiving time

Before I introduced you to the Java operation class about time, do you have such a problem in springMvc?

  • LocalDateTime type conversion problem
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2020-5-19": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-5-19' could not be parsed at index 5; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2020-5-19": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-5-19' could not be parsed at index 5
 at [Source: (PushbackInputStream); line: 5, column: 17] (through reference chain: com.wpp.springboottime.bean.User["currenttime"])]
Copy the code
  • Date conversion problem
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "1980-09-08 11:30": not a valid representation (error: Failed to parse Date value '1980-09-08 11:30': Cannot parse date "1980-09-08 11:30": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "1980-09-08 11:30": not a valid representation (error: Failed to parse Date value '1980-09-08 11:30': Cannot parse date "1980-09-08 11:30": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))
 at [Source: (PushbackInputStream); line: 4, column: 14] (through reference chain: com.wpp.springboottime.bean.User["birthday"])]
Copy the code
  • The front-end time is not formatted

Global processing

Processing Date type

spring: jackson: # Parameter meaning: Default # # JsonInclude. Include. ALWAYS JsonInclude. Include the NON_DEFAULT attribute to serialize # JsonInclude default values Include the NON_EMPTY attribute is null (" ") or for # jsoninclude.include.non_null null-property-inclusion: ALWAYS time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ssCopy the code

Handles the LocalDateTime type

@configuration public class DateformatConfig {/** * Dateformat String */ Private static final String DATE_FORMAT = "yyyy-MM-dd"; */ Private static final String DATETIME_FORMAT = "YYYY-MM-DD HH: MM :ss"; /** * DateTime Format String */ Private static final String DATETIME_FORMAT =" YYYY-MM-DD HH: MM :ss"; /** * Time Format String */ Private static final String TIME_FORMAT = "HH:mm:ss"; / * * * * * @ custom Bean return * / @ Bean @ Primary public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT))) .serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT))) .serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT))) .deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT))) .deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT))) .deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT))); }}Copy the code

Local general method

@dateTimeFormat, @dateTimeFormat for LocalDateTime, Date conversion problems are common

  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
Copy the code