The example in this article describes the Java simple way of doing time. Share to everyone for your reference. The specific analysis is as follows:
The Date used here refers to java.util.Date.
PS: Use Java operation time feel really real eggs pain, or I am big C # Comfortable, a datetime all buttoned up
Get the current time:
Copy Code code as follows:
Create a Date object for the current time
Date time = new Date ();
Where the egg aches, to the time increase, reduce operation:
Copy Code code as follows:
Use the Calendar class to increase and subtract operations
Calendar C = calendar.getinstance ()//Get a calendar instance that is an abstract class so you cannot use the new construct method
Create a time using the SetTime method, which is the date type
C.settime (time);
Adds 12 months to the current time, depending on the Calendar enumeration value to add units
C.add (Calendar.month, 12);
Convert Calendar to Date object
Date dateTime = C.gettime ();
The place where the egg aches again, format the time, convenient for people to look at the format:
Copy Code code as follows:
Use SimpleDateFormat to format time as a string
String timestr = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"). Format (time);
Simple operation, Memo:
Convenient timestamp conversion:
Copy Code code as follows:
/**
* Turn time objects into timestamps
*
* @param time
* Time
* @return Time stamp
*/
public static long Datetolong (Date time) {
try {
Long Timel = Time.gettime ();
System.out.print (Timel);
return Timel;
catch (Exception e) {
E.printstacktrace ();
return 0;
}
}
/**
* Convert time stamp to time object
*
* @param time
* Time stamp
* @return Time Object
*/
public static Date Longtodate (long time) {
Date date = null;
try {
Date = new Date (time);
SYSTEM.OUT.PRINTLN (date);
catch (Exception e) {
E.printstacktrace ();
}
return date;
}
I hope this article will help you with your Java programming.