Home > Java > Javagetting Started > Examples of the Calendar class in java

Examples of the Calendar class in java

王林
Release: 2020-07-23 17:10:03
forward
2435 people have browsed it

Examples of the Calendar class in java

Calendar class, it is an abstract class that encapsulates all calendar field values. The values ​​can be obtained through a unified method based on the different calendar fields passed in.

(Recommended tutorial: java introductory tutorial)

1. Get a calendar object

Calendar c = Calendar.getInstance();//返回的是子类对象
Copy after login

2.Member method

public void add(int field,int amount):根据给定的日历字段和对应的时间,来对当前的日历进行操作。
public final void set(int year,int month,int date):设置当前日历的年月日
Copy after login

(Video tutorial recommendation: java video tutorial)

Code implementation:

import java.util.Calendar;
 
/*
 * public void add(int field,int amount):根据给定的日历字段和对应的时间,来对当前的日历进行操作。
 * public final void set(int year,int month,int date):设置当前日历的年月日
 */
public class CalendarDemo {
	public static void main(String[] args) {
		// 获取当前的日历时间
		Calendar c = Calendar.getInstance();
 
		// 获取年
		int year = c.get(Calendar.YEAR);
		// 获取月
		int month = c.get(Calendar.MONTH);
		// 获取日
		int date = c.get(Calendar.DATE);
		System.out.println(year + "年" + (month + 1) + "月" + date + "日");
 
		// // 三年前的今天
		// c.add(Calendar.YEAR, -3);
		// // 获取年
		// year = c.get(Calendar.YEAR);
		// // 获取月
		// month = c.get(Calendar.MONTH);
		// // 获取日
		// date = c.get(Calendar.DATE);
		// System.out.println(year + "年" + (month + 1) + "月" + date + "日");
 
		// 5年后的10天前
		c.add(Calendar.YEAR, 5);
		c.add(Calendar.DATE, -10);
		// 获取年
		year = c.get(Calendar.YEAR);
		// 获取月
		month = c.get(Calendar.MONTH);
		// 获取日
		date = c.get(Calendar.DATE);
		System.out.println(year + "年" + (month + 1) + "月" + date + "日");
		System.out.println("--------------");
 
		c.set(2011, 11, 11);
		// 获取年
		year = c.get(Calendar.YEAR);
		// 获取月
		month = c.get(Calendar.MONTH);
		// 获取日
		date = c.get(Calendar.DATE);
		System.out.println(year + "年" + (month + 1) + "月" + date + "日");
	}
}
Copy after login

The above is the detailed content of Examples of the Calendar class in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template