The example in this article describes the simple operation method of time in Java. Share it with everyone for your reference. The specific analysis is as follows:
The Date used here refers to java.util.Date.
ps: It feels really painful to use Java to manipulate time, but I am more comfortable with C#. I can do it all with one DateTime.
Get the current time:
Copy the code. The code is as follows: // Create a Date object of the current time
Date time = new Date();
The annoying part is to increase or decrease time:
Copy the code as follows: Use the Calendar class to increase and decrease time
Calendar c = Calendar.getInstance(); // Obtain a Calendar instance. This class is an abstract class so the new constructor cannot be used.
// Use the setTime method to create a time. This time is of Date type.
c.setTime(time);
// Add 12 months to the current time. The unit can be changed according to the Calendar enumeration value.
c.add(Calendar.MONTH, 12);
//Convert Calendar to Date object
Date dateTime = c.getTime();
The annoying part again is formatting the time in a format that is easier for people to read:
Copy the code as follows: Use SimpleDateFormat to format time into a string
String timeStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time);
Simple operation, reminder:
Convenient timestamp conversion:
Copy the code code as follows:/**
* Convert time object into timestamp
*
* @param time
* time
* @return timestamp
*/
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 timestamp to time object
*
* @param time
* timestamp
* @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 be helpful to everyone’s Java programming.