java.util-Date、Calendar、Random类等
一、Date
1.1 使用Date类表示时间
使用Date类表示当前系统时间
Date d = new Date(); System.out.println(d);
使用Date类表示指定的时间
Date d = new Date(); int year = d.getYear() + 1980; // 年份 int month = d.getMonth + 1; // 月份 int date = d.getDate(); // 日期 int hours = d.getHours(); // 小时 int minutes = d.getMinutes(); // 分钟 int seconds = d.getSeconds(); // 秒 int day = d.getDay(); // 星期
Date对象和相对时间转换
Date d = new Date(2016-1900,3-1,10); long time = 1293589521455L; // 将Date类转换成相对时间 long t = d.getTime(); // 将相对时间转换为Date类 Date d1 = new Date(time);
二、Calendar
2.1 使用Calendar类表示时间
使用Calendar类表示当前时间
Calendar c = Calendar.getInstace();
使用Calendar类表示指定时间
Calendar c = Calendar.getInstace(); c.set(2016,3 - 1,9n);
获得Calendar类中的信息
Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); // 年份 int month = c.get(Calendar.MONTH) + 1; // 月份 int date = c.get(Calendar.DATE); // 日期 int hour = c.get(Calendar.HOUR_OF_DAY); // 小时 int minute = c.get(Calendar.MINUTE); // 分钟 int second = c.get(Calendar.SECOND); // 秒 int day = c.get(Calendar.DAY_OF_WEEK); // 星期
三、Random
3.1 构造方法
- public Random():默认种子,是当前时间的毫秒值
- public Random(long seed):给出指定的种子,随机数不变
3.2 成员方法
- public int nextInt():返回int范围内的随机数
- public int nextInt(int n):返回0-n之间的随机数
四、Arrays
4.1 常用方法
- static String toString(int [] a):把数组转换成字符串
- static void sort(int[] a):对数组中的元素进行排序
- static int binarySearch(int [] a, int key):二分法查询
五、Scanner
5.1 构造方法
- Scanner sc = new Scanner(System.in);
- System.in为标准的输入流,对应着键盘录入
5.2 常用方法
- boolen hasNextXxx():判断是否为某类型的元素
Xxx nextXxx():获取该元素
注意
- 先获取数值(int)再获取其他类型会出现问题,这是换行符号的原因
- 解决:先获取数值,再重新创建对象获取其他类型