Math类
包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
使用Math类可以有两种方式:
1、直接使用(Math所在的包java.lang为默认引入的包)
2、使用import static java.lang.Math.abs;静态导入
Random类
生成伪随机数流
日期操作类
Date类
类Date表示特定的瞬间,精确到毫秒,也就是程序运行时的当前时间。
Date date = new Date();//实例化Date对象,表示当前时间
Calendar类
日历类,使用此类可以将时间精确到毫秒显示。
//两种实例化方式
Calendar c = Calendar .getLnstance();
Calendar c = new GregorianCalendar();
DateFormat类及子类SimpleDateFormat
实例综合代码:
package com.booy1;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
public class MathRandomTest {
public static void main(String[] args) {
//圆周率的近似值
System.out.println(Math.PI);
//自然对数e的近似值
System.out.println(Math.E);
//double值的绝对值
System.out.println(Math.abs(-10));
//0到1之间double值的绝对值的正号随机数
System.out.println(Math.random());
//返回接近参数并等于某一整数的double值
System.out.println(Math.round(Math.random()*1000)/100.0);
//求平方根
System.out.println(Math.sqrt(2));
System.out.println("-------------Random-----------");
Random r = new Random();
System.out.println(r.nextLong());
System.out.println("-------------Date-----------");
Date date = new Date();
System.out.println(date);
//使用两个构造方法
//Date(long date)参数是毫秒
//Date()
System.out.println("-------------Calendar-----------");
Calendar c1 = Calendar.getInstance();
Calendar c2 = new GregorianCalendar();
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
int day = c1.get(Calendar.DAY_OF_MONTH);
int hour = c1.get(Calendar.HOUR_OF_DAY);
int minute = c1.get(Calendar.MINUTE);
int second = c1.get(Calendar.SECOND);
int millisecond = c1.get(Calendar.MILLISECOND);
StringBuilder sb = new StringBuilder(50);
sb.append(year).append("年").append(month).append("月").append(day).append("日").append(hour)
.append("时").append(minute).append("分").append(second).append("秒").append(millisecond).append("毫秒");
System.out.println(sb.toString());
System.out.println("-------------DateFormat-----------");
//日期格式化
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss SSS");
String nowDate = df.format(new Date());
System.out.println(nowDate);
}
}
/**
运行结果:
3.141592653589793
2.718281828459045
10
0.9069523047145955
0.02
1.4142135623730951
-------------Random-----------
-2458300247899345049
-------------Date-----------
Fri May 08 12:08:26 CST 2020
-------------Calendar-----------
2020年4月8日12时8分26秒150毫秒
-------------DateFormat-----------
2020年05月08日12:08:26 192
*/