Description: FromLocaldate API, mainly used for fast access to the current day and month, and Dateformatter is basically accompanied by the use. If you are manipulating a Date object, it is mainly used for timestamps, etc., along with SimpleDateFormat. 1.Java 7 and previous versions
1.1. using Java.util.Calendar(not recommended)
Import java.text.ParseException;Import Java. text. SimpleDateFormat;Import Java. util. Calendar;Import Java. util.Date;Public class Demo {public static void main(string[] args)throws ParseException {Date Date= new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Parse ("2015-09-17 20:27:00");Calendar Now= Calendar.getinstance (); Now. SetTime (Date);int Year= Now.get (calendar.year);int month= Now.get (calendar.month) + 1; 0-based! int Day= Now.get (Calendar.day_of_month);System. OUT.PRINTLN ("Year:" + year);System. OUT.PRINTLN ("Month:" + month);System. Out.println ("Day:" + day); }}
Note: It is not recommended to use the global calendar, you can go directly to new SimpleDateFormat (). Getcalendar ()
The results are as follows:
year:2015917
1.2,joda-time(recommended)
Importorg.joda.time.LocalDate;ImportOrg.joda.time.format.DateTimeFormat;ImportOrg.joda.time.format.DateTimeFormatter; Public classDemo { Public Static voidMain (string[] args) {DateTimeFormatter formatter= Datetimeformat.forpattern ("Yyyy-mm-dd HH:mm:ss"); Localdate localdate= Formatter.parselocaldate ("2015-09-17 20:27:00"); System.out.println ("Yearofcentury:" +Localdate.getyearofcentury ()); System.out.println ("Monthofyear:" +localdate.getmonthofyear ()); System.out.println ("DayOfMonth:" +localdate.getdayofmonth ()); }}
The results are as follows:
Yearofcentury:15917
2, JAva 8, directly using the new DateTime API (recommended!!) )
ImportJava.time.LocalDateTime;ImportJava.time.format.DateTimeFormatter; Public classDemo { Public Static voidMain (string[] args) {DateTimeFormatter formatter= Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss"); LocalDateTime Ldt= Localdatetime.parse ("2015-09-17 20:27:00", formatter); System.out.println ("Year:" +ldt.getyear ()); System.out.println ("Month:" +ldt.getmonth (). GetValue ()); System.out.println ("DayOfMonth:" +ldt.getdayofmonth ()); }}
The results are as follows:
year:2015917
Description
- The DateTime APIs provided by Java 8 refer to Jodatime, so they look similar, and if you are using the Java 8 datetime API, you should also consider whether the database driver supports the API when you want to store datetime in the database
- Java 7 and previous versions, recommended to use Jodatime, save time and effort worry
Example Project: Https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test29/test1
Reference:
https://www.zhihu.com/question/35650798 (the above content is transferred from this article)
Java gets the specified time (RPM)