Date type Most time component calculation method has been replaced by calendar
Date Common method SetTime GetTime ()
new Date (); Gets the current time by default
SimpleDateFormat specific classes used to format and parse dates
String that matches the date
Y–> year
M–> Month
D–> Day
E–> Week
A–> last Afternoon
H–> hours (24-hour system)
H–> hours (12-hour system)
M–> min
S–> sec
Format date return value to string
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String result = sdf.format(newDate());System.out.println(result);
Output: 2015-07-22 21:17:43
Resolves a string to date
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String"2015-07-22 21:21:01";Datedate = sdf.parse(strDate);System.out.println(date);
Output Result:
Wed Jul 21:21:01 CST 2015
Calender encapsulates the calendar information
Common methods:
GetInstance () Gets the subclass of a calender in the region where the system is implemented
Typically used to instantiate a calendar
Set (int field,int value) setting time
Get (int field) gets the corresponding value of the time component
Getactualmaximum (int field) Gets the maximum value of the time component
Add () calculates the time component
SetTime and GetTime methods set and get time
Comprehensive application:
Product Promotion Calculation Program
Demand:
The user enters the product production date and the shelf life, calculates the promotion date through the program
Calculation rules:
Until the expiry date of the 14 Tim Wednesday is the promotion day
Public classpromotiondate { Public Static void Main(string[] args) throws Exception {Calendar cd = Calendar.getinstance (); SimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd"); Scanner sc =NewScanner (System.inch); System. out. Print ("Please enter the production date:"); Date productiondate= Sdf.parse (Sc.nextline ());//Receive string and convert to date typeSystem. out. Print ("Please enter the shelf life:");intDays = Sc.nextint (); Cd.settime (productiondate); Cd.add (Calendar.day_of_year, (Days- -)); Cd.Set(Calendar.day_of_week, Calendar.wednesday); String promotiondate = Sdf.format (Cd.gettime ());//Date after format calculationSystem. out. println ("The promotion date for this product is:"+ promotiondate); Sc.close (); }}
Test results:
Please enter production Date: 2015-01-01
Please enter the shelf life: 180
The promotion date for this product is: 2015-06-17
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Common Date Operation detailed