Java time Conversion

Source: Internet
Author: User

For a project, you need to compare the time and period. If it is not convenient to operate in the database, the time operation is placed in the Java program. The following is a string-type time after subtracting one day, one month, and then converting to a string-type time after one year.

Import java. Text. parseexception;

Import java. Text. simpledateformat;
Import java. util. calendar;
Import java. util. date;

Public class du03 {

Public static void main (string [] ARGs ){

String time = "20111224 ";

Try {
Simpledateformat df = new simpledateformat ("yyyymmdd"); // defines the conversion format
Date = DF. parse (time); // convert the string to the time format Using parse

Calendar Cal = calendar. getinstance (); // obtain this class instance.
Cal. settime (date); // convert the date format to the Cal type

Cal. Add (calendar. Date,-1); // minus one for calendar days
Date yesterday = Cal. gettime (); // convert Cal to date yesterday
String yesday = DF. Format (yesterday); // convert date to string format using format
System. Out. println ("yesterday:" + yesday );

Cal. Add (calendar. date, 1 );
Cal. Add (calendar. Month,-1 );
Date lastmonthsameday = Cal. gettime (); // last month
String lastmonth = DF. Format (lastmonthsameday );
System. Out. println ("last month:" + lastmonth );

Cal. Add (calendar. month, 1 );
Cal. Add (calendar. Year,-1 );
Date lastyearsameday = Cal. gettime (); // last year
String lastyear = DF. Format (lastyearsameday );
System. Out. println ("last year:" + lastyear );

} Catch (parseexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}

}

}

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.