第12次作业--你的生日
题目:利用Calendar类计算自己的出生日期距今天多少天,再将自己的出生日期利用SimpleDateFormat类设定的格式输出显示。
代码:
package youolddays; import java.text.ParseException; mport java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import org.junit.Test; public class yourdaydemo { @Test public void fun() throws ParseException { Scanner sc = new Scanner(System.in); System.out.println("输入你的出生日期:"); String bornDay = sc.nextLine(); int days = getLifeDay(bornDay); System.out.println("你已经来到了这个世界" + days + "天."); } public int getLifeDay(String bornDay) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); Date d = sdf.parse(bornDay); long bornTime = d.getTime(); long currentTime = System.currentTimeMillis(); long times = currentTime - bornTime; int days = (int) (times / 1000 / 60 / 60 / 24); return days; } }
运行结果: