《系统常用类(二)》
目录
一、日期类
系统时间获取
- System.currentTimeMillis():返回当前时间与 1970 年 1 月 1 日午夜之间的时间差(单位:毫秒)。
long start = System.currentTimeMillis();
//程序段…
long end = System.currentTimeMillis();
System.out.println("程序段执行所用时间:"+(end-start)+"毫秒");
日期类(DateFormat>SimpleDateFormat)
- 常用构造方法
Date()
Date(long date)
- 常用方法
boolean after(Date when); //判断是否在指定日期之后
boolean before(Date when); //判断是否在指定日期之前
日期格式化
- 模式字符
字符 | 含义 |
---|---|
y | 年 |
M | 月 |
d | 日 |
E | 星期 |
H | 小时(0-23) |
h | 小时am/pm(1-12) |
m | 分钟 |
s | 秒 |
S | 毫秒 |
- 代码示例
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("----------------日期转字符串----------------");
Date date = new Date();
String format = sdf.format(date);
System.out.println(format);
System.out.println("----------------字符串转日期----------------");
try {
String str = "2010-10-1 11:30:10";
Date parse = sdf.parse(str);
System.out.println(parse);
} catch (ParseException e) {
e.printStackTrace();
}
执行结果
日历类(Calender)
- 常用方法
static Calendar getInstance(); //获取日历实例
Date getTime(); //获取时间
void set(int field, int value); //设置字段值
int get(int field); //获取字段值
void setTime(Date date); //设置时间
- 代码示例(假设今天生产一个食品,60天过期,计算它的过期日期)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar instance = Calendar.getInstance();
System.out.println("生产日期:" + sdf.format(instance.getTime()));
instance.add(Calendar.DAY_OF_MONTH, 60);
System.out.println("过期日期:" + sdf.format(instance.getTime()));
执行结果
二、数字类
工具类(Math)
//常量
static double E
static double PI
//常用的方法
static double abs(double a); //求绝对值
static double ceil(double a); //求天花板值
static double floor(double a); //求地板值
static long round(double a); //四舍五入
static double pow(double a, double b); //求次方
static double random(); //随机小数[0,1)
static double max(double a,double b); //判断两者更大值
static double min(double a,double b); //判断两者更小值
随机数(java.util.Random)
Random random = new Random();
int x = random.nextInt(n); //随机整数,范围[0,n)
精度计算(BigDecimal)
八大基本数据类型最大只有8字节,范围有限,因此当操作更大位数数字时,就需要BigDecimal了。
BigDecimal a = new BigDecimal("10");
BigDecimal b = new BigDecimal("3");
BigDecimal add = a.add(b); //加法
BigDecimal subtract = a.subtract(b); //减法
BigDecimal multiply = a.multiply(b); //乘法
BigDecimal divide = a.divide(b, BigDecimal.ROUND_HALF_UP); //除法
BigDecimal aa = a.setScale(BigDecimal.ROUND_HALF_UP, 2); //设置取值模式(例如当前四舍五入)
数字格式化(NumberFormat>DecimalFormat)
- NumberFormat
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(3); //设置最大整数位数
nf.setMaximumFractionDigits(2); //设置最大小数位数
nf.setMinimumIntegerDigits(1); //设置最小整数位数
nf.setMinimumFractionDigits(1); //设置最小小数位数
String format = nf.format(1234.5678);
System.out.println(format); //234.57
- DecimalFormat
DecimalFormat df = new DecimalFormat("00.##");
System.out.println(df.format(1.3456)); //01.35
总结
重点
- 日期格式化;
- 日历类使用;
- 数字格式化。
难点
- 日期格式化pattern;
- DecimalFormat模式0与#的使用。