Math,Date,DateFormat和Calendar

 * Math

 * 成员变量:

 * public static final double PI 
 * public static final double E
 * 成员方法:
 *   public static int abs(int a):绝对值
 * public static double ceil(double a):向上取整
 * public static double floor(double a):向下取整
 * public static int max(int a,int b):最大值 
 * public static double pow(double a,double b):a的b次幂
 * public static double random():随机数 [0.0,1.0)
 * public static int round(float a) 四舍五入

 * public static double sqrt(double a):正平方根

 * Date表示特定的时间,精确到毫秒
 * 构造方法:
 * Date() :根据当前的默认毫秒值创建日期对象
 * Date(long date) :根据给定的毫秒值创建日期对象
 *  Date --> String(格式化)
 * public final String format(Date date)
 * 
 *  String   --> Date(解析)
 * public Date parse(String source)
 * 
 * DateForamt:可以进行日期和字符串的格式化和解析,但是由于是抽象类,所以使用具体子类SimpleDateFormat。
 * 
 * SimpleDateFormat的构造方法:
 * SimpleDateFormat():默认模式

 * SimpleDateFormat(String pattern):给定的模式

 * 需求:根据键盘录入出生时间,计算来到世界多少天
 * 分析:
 * a:键盘录入出生年月日
 * b:把该字符串转为一个日期值
 * c:将日期值转为毫秒值
 * d:获取当前时间的毫秒值
 * e:用d-c得到一个毫秒值

 * f:作e/1000/60/60/24操作

                Scanner sc = new Scanner(System.in);
System.out.println("请输入你的出生年月日: ");
String birthDays = sc.nextLine();
//将该字符串转为日期值
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(birthDays);
//将日期值转为毫秒值
long time = date.getTime();
//获取当前时间的毫秒值
long nowTime = System.currentTimeMillis();

long stayTime = nowTime - time;
long days = stayTime/1000/60/60/24;

System.out.println("你来到这个世界" + days + "天");

     //Calendar是一个抽象类,实例调用的时候必须用子类对象实现
Calendar ca = Calendar.getInstance();
//获取年
int year = ca.get(Calendar.YEAR);
int month = ca.get(Calendar.MONTH) +1; //月份默认是从0开始计算
int day = ca.get(Calendar.DAY_OF_MONTH);
System.out.println(year + "年" +month+ "月"+day+"日");
//3年前的今天
ca.add(Calendar.YEAR, -3);
 
year = ca.get(Calendar.YEAR);
month = ca.get(Calendar.MONTH) +1;
day = ca.get(Calendar.DAY_OF_MONTH);
System.out.println("三年前的今天是: " +year + "年" + month + "月" + day + "日");

猜你喜欢

转载自blog.csdn.net/u012858008/article/details/80511729