
Date与Calendar类
发布日期:2021-05-06 15:34:51
浏览次数:19
分类:技术文章
本文共 1458 字,大约阅读时间需要 4 分钟。
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);