第12次作业--你的生日
题目:利用Calendar类计算自己的出生日期距今天多少天,再将自己的出生日期利用SimpleDateFormat类设定的格式输出显示。
代码:
package factorial; import java.text.SimpleDateFormat; import java.util.*; public class Birthday { public static void main(String[] args) { Scanner input = new Scanner(System.in); Calendar calendar = Calendar.getInstance(); System.out.println("请输入你的生日:"); String birthdaytime = input.nextLine(); StringTokenizer time = new StringTokenizer(birthdaytime," ,.-"); //以 ,.-分割做拆分 String stringyear = null,stringmonth = null,stringday = null; //拆分 while(time.hasMoreTokens()) { int count = time.countTokens(); if(count == 3) stringyear = time.nextToken(); else if(count == 2) stringmonth = time.nextToken(); else if(count == 1) stringday = time.nextToken(); } //字符串转化数字 int year = Integer.parseInt(stringyear); int month = Integer.parseInt(stringmonth); int day = Integer.parseInt(stringday); //Calendar类 calendar.set(year, month - 1, day); SimpleDateFormat birthday = new SimpleDateFormat("YYYY年MM月dd日"); System.out.println(birthday.format(calendar.getTimeInMillis())); //Date类 Date nowTime = new Date(); System.out.println("您出生了" + (nowTime.getTime() - calendar.getTimeInMillis())/1000/60/60/24 + "天"); } }
结果:
多种格式输入: