Calendar #
Calendar的三个放
- get
- set
- add
好用的日期类型 #
LocalDate: 本地化的日期
LocalTime:本地化的时间
LocalDateTime: 本地化的日期+时间
DateTimeFormatter : java.time,Local系列与字符串转换。
// Local本地的日期
LocalDate date = LocalDate.now();
System.out.println(date); // yyyy-MM-dd0
System.out.println(date.getYear());
System.out.println(date.getMonthValue()); // 当前的月份
System.out.println(date.getDayOfMonth());
System.out.println(date.getDayOfWeek().getValue()); // 第几天,周日是第7天
// HH-mm-ss.SSS
LocalTime time = LocalTime.now();
System.out.println(time);
System.out.println(time.getHour());
System.out.println(time.getMinute());
System.out.println(time.getSecond());
LocalDateTime ldt = LocalDateTime.of(2022, 1, 31, 23, 59, 59);
System.out.println(ldt);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
// LocalDateTime ==> String
String str = dtf.format(ldt);
System.out.println(str);
// String ===> LocalDateTime
String str1 = "1995年02月01日 12时13分14秒";
LocalDateTime ldt1 = LocalDateTime.parse(str1, dtf);
System.out.println(ldt1);
BigInteger #
基本类型存不下或运算不了的情况下,用堆内存来计算。
- BigInteger add(BigInteger bi); 加法运算
- Biginteger substract(BigInteger bi); 减法运算
- Biginteger multiply(BigInteger bi): 乘法运算
- Biginteger divide(BigInteger bi): 除法运算
// 100的阶乘
BigInteger result3 = new BigInteger("1");
BigInteger bi = new BigInteger("100");
for (BigInteger i = new BigInteger("1"); i.compareTo(bi) <= 0; i = i.add(new BigInteger("1"))) {
result3 = result3.multiply(i);
}
System.out.println(result3);
BigDecimal #
基本类型double不可运算。尤其在金额方面。(财务项目,金融项目,电商项目。。)必须用BigDecimal
- BigDecimal add(BigDecimal bi); 加法运算
- BigDecimal substract(BigDecimal bi); 减法运算
- BigDecimal multiply(BigDecimal bi): 乘法运算
- BigDecimal divide(BigDecimal bi): 除法运算
除法非常特殊
BigDecimal big = new BigDecimal(1);
BigDecimal thre = new BigDecimal("3");
// 直接除,ArthmeticException:无限循环小数
// BigDecimal result = big.divide(thre);
// 2scale小数位数, 舍入模式
BigDecimal result = big.divide(thre, 2, RoundingMode.HALF_UP);
System.out.println(result);
// MathContext.DECIMAL128 计算的数学位数 32 - 7 64 - 16 128 32
BigDecimal result1 = big.divide(thre, MathContext.DECIMAL128);
BigDecimal result2 = result1.setScale(2, RoundingMode.CEILING);
System.out.println(result1);
System.out.println(result2);
java.lang.Math #
- abs(); 绝对值
- ceil(); 返回大于或等于参数的最小(最接近负无穷大) double值,等于一个数学整数。
- floor(); 数轴取左
- round(); 四舍五入
- random(); 随机数
- pow(); 幂运算
Math.abc(-1); 1
Math.ceil(3.1); // 4.0
Math.floor(3.1); // 3
Math.pow(2, 2); // 4.0
Math.round(3.1415926); // 3
Math.random(); [0, 1)