Java's simple manipulation of time
- 2020-04-01 03:37:20
- OfStack
This article illustrates a simple way to manipulate time in Java. Share with you for your reference. Specific analysis is as follows:
The Date used here refers to java.util.Date.
Ps: using Java operation time feel really really painful, or I am comfortable with C#, a DateTime all done
Get current time:
//Create a Date object
for the current time
Date time = new Date();
Where the egg hurts, increase or decrease the operation of time:
//Use the Calendar class to add or subtract time
Calendar c = Calendar.getInstance();//Gets a Calendar instance, which is an abstract class so you can't use the new constructor
//Use the setTime method to create a time of type Date
c.setTime(time);
//Add 12 months to the current time, add units
depending on the Calendar enumeration value
c.add(Calendar.MONTH, 12);
//Turn Calendar into a Date object
Date dateTime = c.getTime();
Again egg sore place, format time, convenient for people to see the format:
//Use SimpleDateFormat to format the time as a string
String timeStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time);
Simple operation, memo:
Convenient timestamp conversion:
/**
* Converts a time object to a timestamp
*
* @param time
* time
* @return The 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;
}
}
/**
* Converts a timestamp to a time object
*
* @param time
* The 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 has been helpful to your Java programming.