Java Simple example of the operation of time _java

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.