设计日期类
【问题描述】借助Calendar类,设计一个日期类MyDate,能根据多种输入数据创建日期对象,可对日期进行计算,并以不同的模式输出日期。类图如下:
【输入形式】1-8的整数
【输出形式】输入1,则输出2010-10-10
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
//-----以下为需填片段-------
class MyDate {
Calendar c = Calendar.getInstance();
String pattern = "yyyy-MM-dd";
public MyDate() {
}
public MyDate(int y, int m, int d) {
c.set(y, m - 1, d);
}
public MyDate(String source) {
SimpleDateFormat sf = new SimpleDateFormat(pattern);
Date d = new Date();
try {
d = sf.parse(source);
c.setTime(d);
} catch (ParseException e) {
e.printStackTrace();
}
}
public MyDate(String source, String pattern) {
SimpleDateFormat sf = new SimpleDateFormat(pattern);
setPattern(pattern);
Date d = new Date();
try {
d = sf.parse(source);
c.setTime(d);
} catch (ParseException e) {
e.printStackTrace();
}
}
public MyDate after(int n) {
c.add(Calendar.DATE, n);
return new MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DATE));
}
public MyDate before(int n) {
c.add(Calendar.DATE, -n);
return new MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DATE));
}
public Date getDate() {
return c.getTime();
}
public Calendar getCalendar() {
return c;
}
public long getLong() {
return c.getTimeInMillis();
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String toString() {
SimpleDateFormat sf = new SimpleDateFormat(pattern);
return sf.format(c.getTime());
}
}
//--------------------------
public class Main {
public static void main(String[] args) {
int selected;
Scanner in=new Scanner(System.in);
selected=in.nextInt();
MyDate md=new MyDate(2000,10,10);
switch(selected){
case 1:
System.out.println(md);
break;
case 2:
md=new MyDate("2010-10-10");
System.out.println(md);
break;
case 3:
md=new MyDate("2010/10/10","yyyy/MM/dd");
System.out.println(md);
break;
case 4:
System.out.println(md.after(8));
break;
case 5:
System.out.println(md.before(20));
break;
case 6:
System.out.println(md.getCalendar().get(Calendar.YEAR));
break;
case 7:
md.setPattern("yyyy/MM/dd");
System.out.println(md);
}
in.close();
}
}
记录Java面向对象课程练习题,方便查阅。如有错误,恳请指出。
标签:md,Java,pattern,MyDate,面向对象,new,程序设计,Calendar,public From: https://www.cnblogs.com/zhuannnn/p/18004377