English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Common Methods of Date and Calendar in Java

The most commonly used time class in Java is java.util.Date, since the getYear(), getMonth() and other methods to get year, month, day, week, etc. in the Date class have been deprecated, so we need to rely on Calendar to get commonly used date formats such as year, month, day, week, etc.

Note:The following code has been tested in jdk1.6This has passed in the test, other versions may use different, please note! 

Interconversion methods between Date and String

/**
 * Interconversion methods between Date and String, here SimpleDateFormat is needed
 */
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");-MM-dd");
String dateString = formatter.format(currentTime);
Date date = formatter.parse(dateString);

Interconversion between Date and Calendar

/**
 * Interconversion between Date and Calendar
 */
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
Date date1 = cal.getTime();

Use Calendar to obtain year, month, week, day, hour, etc. time domain

/**
 * Use Calendar to obtain year, month, week, day, hour, etc. time domain
 */
cal.get(Calendar.YEAR);
cal.get(Calendar.MONTH);
cal.get(Calendar.WEEK_OF_MONTH);
cal.get(Calendar.DAY_OF_MONTH);

Add or subtract time

/**
 * Add or subtract time
 */
cal.add(Calendar.MONTH, 1);
System.out.println(cal.getTime());

Calculate the day of the week for a given date

Calendar cal = Calendar.getInstance();
cal.set(2016,08,01);
String[] strDays = new String[] { "SUNDAY", "MONDAY", "TUESDAY",
         "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"
        };
System.out.println(strDays[cal.get(Calendar.DAY_OF_WEEK) - 1);

That's all for this article, hope it helps your learning, and also hope everyone supports the Yelling Tutorial more.

Statement: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any suspected copyright content, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the infringing content.)

You May Also Like