# # # #1. Date
Date: The main use is *java.util.date* and *java.sql.date*,
The date in SQL is a subclass of date in Util, and the relationship is as follows, but cast conversion errors occur if you convert directly.
-Java.lang.Object
-Java.util.Date
-Java.sql.Date
Conversions can be done through the following example:
"' Java
Java.util.Date utildate=new java.util.Date (System.getcurrenttime ());
Java.sql.Date sqldate=new java.sql.Date (Utildate.gettime ());
```
This is the way to convert due to SQL. Date is a subclass of util.date, so you can assign sql.date to util.date directly.
##### 2. Date and string
The conversion between dates and strings is done primarily through the SimpleDateFormat class, and the relationship between them is as follows:
-Java.lang.Object
-Java.text.Format
-Java.text.DateFormat
-Java.text.SimpleDateFormat
DateFormat is an abstract class, the direct subclass is the SimpleDateFormat class, when used, you need to first specify the type of date/string to convert, that is, the rules of the conversion, including the string---> Date and
Date---> String two cases, as follows:
"' Java
SimpleDateFormat sdf1=new SimpleDateFormat ("Yyyy-mm-dd");
SimpleDateFormat sdf2=new SimpleDateFormat ("Yyyy-mm-dd hh:MM:ss");
```
One includes the time, the former does not include the time.
==*simpledateformat two important methods for string and date conversions are format () and parse () *==;
**format (): Date turns into String * *.
**parse (); The string is converted to a date * *.
In addition to Prase (), the format () method is applicable to both Java.sql.Date and java.util.Date for the **simpledateformat** class.
##### 3. Time
==java.time== is a new time package in jdk1.8 that provides the processing of date and time consistency.
in Java, there are many problems with the existing date and time-related classes, including:
-Java has inconsistent definitions of date/time classes, There are date classes in Java.util and java.sql packages, and classes for formatting and parsing are defined in the Java.text package.
-Java.util.Date contains both a date and a time, and Java.sql.Date contains only dates, and it is not reasonable to include them in the java.sql package. The other two classes have the same name, which is a very bad design in itself. The
has no explicitly defined classes for time, timestamp, formatting, and parsing. For the requirements of formatting and parsing, we have java.text.DateFormat abstract classes, but typically, the SimpleDateFormat class is used for such requirements.
-All date classes are mutable, so they are not thread-safe, which is one of the biggest problems with the Java date class. The
-date class does not provide internationalization, there is no time zone support, so Java introduces the Java.util.Calendar and Java.util.TimeZone classes, but they also have all of the above problems.
Advantages of the new API:
-invariance: In the new date/Time API, all classes are immutable, which is good for multithreaded environments.
Separation of concerns: the new API explicitly separates human-readable datetime and Machine time (Unix timestamp), which defines different classes for date (date), Time, datetime, timestamp (Unix timestamp), and time zone.
-clear: In all classes, methods are explicitly defined to accomplish the same behavior. For example, to get the current instance we can use the now () method, which defines the format () and the Parse () method in all classes, rather than having a separate class dedicated to it as before. To better handle the problem, all classes use Factory mode and policy mode, and once you use one of these classes, working with other classes is not difficult.
-Practical operation: all new Date/Time API classes implement a series of methods to accomplish common tasks such as add, subtract, format, parse, extract individual parts from date/time, and so on.
-Extensibility: The new Date/Time API is working on the ISO-8601 calendar system, but we can also apply it on non-iOS calendars.
The new API
-Java.time Package: This is the base package for the new Java Date/Time API, and all the main base classes are part of this package, such as: Localdate, LocalTime, LocalDateTime, Instant, Period, Duration and so on. All of these classes are immutable and thread-safe, and in the vast majority of cases, these classes are able to handle some of the public requirements effectively.
-Java.time.format Package: This package contains classes that can format and parse DateTime objects, and in most cases we should not use them directly, because the corresponding classes in the Java.time package already provide methods for formatting and parsing.
-Java.time.temporal Package: This package contains some temporal objects that we can use to find a specific date or time on a date/time object, for example, to find the first or last day of a month. You can recognize these methods very easily, because they all have a "withxxx" format.
-Java.time.zone Package: This package contains classes that support different time zones and related rules.
The Important class
1.LocalDate, date without time zone information, is an immutable Date object, the default form is ==2007-12-03==.
> A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
Localdate is an immutable Date-time object that represents a date, often viewed as year-month-day. Other date fields, such as Day-of-year, Day-of-week and Week-of-year, can also is accessed. For example, the value "2nd October" can is stored in a localdate.
The hierarchy of inheritance is as follows:
>-Java.lang.Object
-Java.time.LocalDate
Common methods (partial):
| Return value type | method Body | Description |
|--------|--------|--------|
| int | CompareTo (chronolocaldate Other) | Compares this date to another date. |
|boolean|equals (Object obj) | Checks If this date is equal to another date.
| String | Format (DateTimeFormatter formatter) | Formats This date using the specified formatter.|
|int|getdayofmonth () | Gets the Day-of-month field.|
| DayOfWeek | GetDayOfWeek () | Gets the Day-of-week field, which is an enum DayOfWeek. |
| int |getdayofyear () | Gets the Day-of-year field. |
| Localdate | Withdayofmonth (int dayofmonth) | Returns a copy of this localdate with the Day-of-month altered. |
| Localdate | Withyear (int year) | Returns a copy of this localdate with the year altered. |
| String | ToString () | Outputs this date as a String, such as 2007-12-03. |
| Static Localdate | of (int year, int month, int dayofmonth) | Obtains an instance of localdate from a year, month and day. |
| Static Localdate | of (int year, month month, int dayofmonth) | Obtains an instance of localdate from a year, month and day. |
| Boolean | Isafter (chronolocaldate Other) | Checks If this date was after the specified date. |
| Boolean |isbefore (Chronolocaldate other) | Checks If this date is before the specified date. |
| Boolean | IsEqual (chronolocaldate Other) | Checks If this date is equal to the specified date. |
| Boolean | Isleapyear () | Checks If the year was a leap year, according to the ISO proleptic calendar system rules. |
2.LocalTime, no time zone information, is an immutable time object, the default form is ==10:15:30==.
> A time without a time-zone in the ISO-8601 calendar system, such as 10:15:30.
LocalTime is an immutable Date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30.123456789" Can is stored in a localtime.
The hierarchy of inheritance is as follows:
>-Java.lang.Object
-Java.time.LocalTime
3.LocalDateTime, no time zone information datetime, is an immutable datetime object, the default form is ==2007-12-03t10:15:30==.
> A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03t10:15:30.
LocalDateTime is an immutable Date-time object that represents a date-time, often viewed as year-month-day-hour-minute-sec Ond. Other date and Time fields, such as Day-of-year, Day-of-week and Week-of-year, can also is accessed. Time is represented to nanosecond precision. For example, the value ' 2nd October at 13:45.30.123456789 ' can be stored in a LocalDateTime.
It should be explained that the above three classes are much the same point, and it implements the ==comparable< chronolocaldatetime< >>== interface, can be through before, After or Compaterto methods compare time, date, etc.,
##### 4. Time, size comparison between dates
Mainly divided into Java.util.Date class and java.time two distinctions, the former through gettime () to obtain a long value subtraction, there are before () and after () two methods, the latter can also be subtracted by getlong () to compare, The results can also be obtained by means of Isafter (), Isbefore (), IsEqual (), and by the CompareTo () method.
##### 5.Joda Time
##### 6. Case Demo
==*useolddate.java*==
"' Java
Package dateandtime;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
/**
* Created by Renjiaxin on 2017/7/26.
*/
public class Useolddate {
public static void Main (string[] args) throws ParseException {
String str1 = "1992-09-12";
String str2 = "2008-12-13 12:14:22";
SimpleDateFormat sdf1 = new SimpleDateFormat ("Yyyy-mm-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat ("Yyyy-mm-dd hh:MM:ss");
Date date1 = Sdf1.parse (STR1);//extract time from string
Date date2 = Sdf2.parse (STR2);
Date Date3 = new Date ();//Get current time
String Str3=sdf2.format (Date3);
Date date4 = new Java.sql.Date (Date1.gettime ());//java.sql.date is a java.util.Date subtype
Java.sql.Date date5 = new Java.sql.Date (Date1.gettime ());//Time to create Java.sql.Date type
String Str4=sdf2.format (Date5);//Time formatted as a string
Date Date6=date5;//java.sql.date is the Java.util.Date subtype
Java.sql.Date Date7=sdf1.parse (STR1);//cannot be directly assigned to the Java.sql.Date type using the extract time from the string
System.out.println (date1);
System.out.println (DATE2);
System.out.println (Date3);
System.out.println (DATE4);
System.out.println (DATE5);
System.out.println (DATE6);
System.out.println ("Time is:" +str3+ ".");
System.out.println ("Time is:" +str4+ ".");
}
}
```
==*usenewtime.java*==
"' Java
Package dateandtime;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import java.time.*;
Import Java.time.format.DateTimeFormatter;
Import Java.util.Date;
/**
* Created by Renjiaxin on 2017/7/26.
*/
public class Usenewtime {
public static void Main (string[] args) throws ParseException {
Localdate
Localdate Localdate1=localdate.of (1992, month.february,12);//define Date
Localdate Localdate2=localdate.of (2009,6,12);
Localdate Localdate3=localdate.ofyearday (2017,118);
Localdate Localdate4=localdate.now ();//Current time
System.out.println (LOCALDATE1);
System.out.println (LOCALDATE2);
System.out.println (LocalDate3);
System.out.println (LOCALDATE4);
Localdate2=localdate2.withdayofyear (234);//Modified Date
System.out.println (LOCALDATE2);
String str1= "2016-09-09";
Localdate Localdate5=localdate.parse (STR1);
String Str2=localdate5.format (datetimeformatter.iso_local_date);//format type, requires STR1 date to be double-digit
System.out.println ("str2:" +STR2);
LocalDateTime
LocalDateTime Localdatetime1=localdatetime.of (2008,5,12,12,24);
LocalDateTime Localdatetime2=localdatetime.now ();
LocalDateTime Localdatetime3=localdatetime1.plusmonths (24);
LocalDateTime localdatetime4=localdatetime2.withdayofyear (112);
Localdate localdate6=localdatetime1.tolocaldate ()//localdatetime turn localdate
Boolean isleapyear=localdate6.isleapyear ();//Common year test
int day=localdatetime1.getdayofyear ();//day of year
DayOfWeek Dw=localdate6.getdayofweek ();//day of week
String Str3=localdatetime3.format (datetimeformatter.iso_local_date_time);
String str4=localdatetime4.tostring ();
System.out.println (LOCALDATETIME1);
System.out.println (localDateTime2);
System.out.println (LocalDateTime3);
System.out.println (LOCALDATETIME4);
System.out.println (LOCALDATE6);
System.out.println ("STR3:" +STR3);
System.out.println ("STR4:" +STR4);
System.out.println ("Isleapyear:" +isleapyear+ ", Day:" +day+ ", DW:" +DW ");
LocalTime
LocalTime Localtime1=localtime.max;
LocalTime Localtime2=localtime.now ();//Current time
LocalTime Localtime3=localtime.of (12,24,36);//Creation time
int Secondofday=localtime3.tosecondofday ();//The first few seconds of the day.
String str5=localtime3.tostring ();
String Str6=localtime3.format (datetimeformatter.iso_local_time);
Boolean isafter=localtime3.isafter (localTime2);//Compare time size
int Comtime=localtime3.compareto (Localdatetime2.tolocaltime ());//convert, and compare time
System.out.println (LOCALTIME1);
System.out.println (localTime2);
System.out.println (LocalTime3);
System.out.println ("Secondofday:" +secondofday);
System.out.println ("STR5:" +STR5);
System.out.println ("STR5:" +STR5);
System.out.println ("Isafter:" +isafter);
System.out.println ("Comtime:" +comtime);
The transformation of old and new, or to become the formal default style, is easy to carry out.
String Temp=localdate1.format (datetimeformatter.iso_date);
SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd");
Java.util.Date Olddate1=sdf.parse (temp);//Conversion
Java.util.Date olddate2=new Date ();
Localdate Localdate7=localdate.parse (Sdf.format (OLDDATE2));//conversion, there is a problem here
SYSTEM.OUT.PRINTLN ("Temp:" +temp);
System.out.println ("oldDate1:" +olddate1);
System.out.println ("OldDate2:" +olddate2);
System.out.println ("LocalDate7:" +localdate7);
}
}
```
==*timecompare.java*==
"' Java
Package dateandtime;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import Java.time.LocalDate;
Import Java.time.LocalDateTime;
Import Java.util.Date;
/**
* Created by Renjiaxin in 2017/7/26.
*/
public class Timecompare {
public static void main (string[ ] args) throws ParseException {
/** old class **/
//gettime ()
Date date1 = new Date ();
String str1 = "2012-09-08";
SimpleDateFormat sdf1 = new SimpleDateFormat ("Yyyy-mm-dd");
Long D1 = Date1.gettime ();
Date Date2=sdf1.parse (STR1);
Long D2 = Date2.gettime ();
Boolean IsBig;
if (D1-d2 > 0) {
isbig= true;
} else {
IsBig = false;
}
System.out.println (date1+ "is bigger than" + date2+ ":" +isbig);
Before (), after ()
Boolean isbefore=date1.after (Date2);
System.out.println (date1+ "is before than" + date2+ ":" +isbefore);
/* NEW class */
Isafter ()
Localdate Localdate1=localdate.now ();
Localdate Localdate2=localdate.of (1999,9,9);
Localdate Localdate3=localdate.of (1999,9,8);
Boolean isafter=localdate1.isafter (LOCALDATE2);
Localdate3.plusdays (1);
Boolean isequal=localdate2.isequal (LocalDate3);
System.out.println (isafter+ "," + isequal);
CompareTo ()
LocalDateTime Localdatetime1=localdatetime.now ();
LocalDateTime Localdatetime2=localdatetime.of (2016,3,6,12,25,56);
int Com=localdatetime1.compareto (localDateTime2);
System.out.println (COM + ".");
}
}
```
Ref
[Conversion between date and string in Java] (http://blog.csdn.net/woshisap/article/details/6742423/)
[Java Date comparison, date calculation] (http://www.cnblogs.com/xu-lei/p/5881899.html)
[Java8 Date/Time (datetime) API Guide] (http://www.importnew.com/14140.html)
Summary of dates in Java