Date與Calendar類
Date是java 1.0版本出現的 從1970年1月1日開始計算 東八區 小時+8
成員方法 public long getTime() 精確到毫秒
public void setTime(long time)
輸入出生日期,輸出到現在第幾天
SimpleDateFormat.parse 解析
SimpleDateFormat.format 格式化
Scanner sc=new Scanner(System.in);
String birthday=sc.nextLine();
Date d=new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
long date=new Date().getTime()-d.getTime();
System.out.println("你來到這個世界已經"+date/1000/60/60/24+"天了");
}
日期與毫秒的相互轉換
日期轉毫秒 date.getTime();
毫秒轉日期 Date date=new Date(long time)
獲取年月日 注意 month 從0開始計算 要+1處理
Calendar類的概述和獲取日曆字段的方法
Calendar c=Calendar.getInstance();
int day=c.get(Calendar.DAY_OF_MONTH);
int month=c.get(Calendar.MONTH);
int year=c.get(Calendar.YEAR);
System.out.println(year+"年"+(month+1)+"月"+day+"日");
public void add(int field,int amount) 根據給定的日曆字段和對應的時間,來對當前的日曆進行操作
public final void set(int year,int month,int date) 設置當前日曆的年月日
c.add(Calendar.YEAR, -3);
day=c.get(Calendar.DAY_OF_MONTH);
month=c.get(Calendar.MONTH);
year=c.get(Calendar.YEAR);
System.out.println(year+"年"+(month+1)+"月"+day+"日");
c.set(1992, 8, 2);
day=c.get(Calendar.DAY_OF_MONTH);
month=c.get(Calendar.MONTH);
year=c.get(Calendar.YEAR);
System.out.println(year+"年"+(month+1)+"月"+day+"日");
求任意年份的2月份天數
Scanner sc=new Scanner(System.in);
int year=sc.nextInt();
Calendar c=Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DAY_OF_MONTH,-1);
int day=c.get(Calendar.DAY_OF_MONTH);
System.out.println(day);
成員方法 public long getTime() 精確到毫秒
public void setTime(long time)
輸入出生日期,輸出到現在第幾天
SimpleDateFormat.parse 解析
SimpleDateFormat.format 格式化
Scanner sc=new Scanner(System.in);
String birthday=sc.nextLine();
Date d=new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
long date=new Date().getTime()-d.getTime();
System.out.println("你來到這個世界已經"+date/1000/60/60/24+"天了");
}
日期與毫秒的相互轉換
日期轉毫秒 date.getTime();
毫秒轉日期 Date date=new Date(long time)
獲取年月日 注意 month 從0開始計算 要+1處理
Calendar類的概述和獲取日曆字段的方法
Calendar c=Calendar.getInstance();
int day=c.get(Calendar.DAY_OF_MONTH);
int month=c.get(Calendar.MONTH);
int year=c.get(Calendar.YEAR);
System.out.println(year+"年"+(month+1)+"月"+day+"日");
public void add(int field,int amount) 根據給定的日曆字段和對應的時間,來對當前的日曆進行操作
public final void set(int year,int month,int date) 設置當前日曆的年月日
c.add(Calendar.YEAR, -3);
day=c.get(Calendar.DAY_OF_MONTH);
month=c.get(Calendar.MONTH);
year=c.get(Calendar.YEAR);
System.out.println(year+"年"+(month+1)+"月"+day+"日");
c.set(1992, 8, 2);
day=c.get(Calendar.DAY_OF_MONTH);
month=c.get(Calendar.MONTH);
year=c.get(Calendar.YEAR);
System.out.println(year+"年"+(month+1)+"月"+day+"日");
求任意年份的2月份天數
Scanner sc=new Scanner(System.in);
int year=sc.nextInt();
Calendar c=Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DAY_OF_MONTH,-1);
int day=c.get(Calendar.DAY_OF_MONTH);
System.out.println(day);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.