一、日期转换
1.常用日期转换
字符串转日期
Date date = sdf.parse( " 2008-07-10 19:20:00 " ); String s = dateTimeResources + "-" + "01" + "-" + "01"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM"); Date date = simpleDateFormat.parse(s); //格式化 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM"); Date y1 = simpleDateFormat.parse(date);
获取年月日
Date date = new Date(); String format = DateFormat.getDateInstance().format(date); List<String> idList = Arrays.asList(format.split("-"));
2.Calendar 与 Date之间的转换
Calendar 转时间戳
Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime().getTime();
Calendar 转Date
Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime();
Date 转换成 Calendar
Date date = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date );
二、字符串和数字类型转换
字符串小数转百分比字符串
DecimalFormat df = new DecimalFormat("0.00%"); System.out.println(df.format(0.1234));
字符串转double
private double convertDouble(String monthTotalWorkLoadStr) { if (monthTotalWorkLoadStr == null || "".equals(monthTotalWorkLoadStr.trim())) { monthTotalWorkLoadStr = "0"; } double monthTotalWorkLoadDouble = Double.parseDouble(monthTotalWorkLoadStr); return monthTotalWorkLoadDouble; }
double 保留小数位数
问题记录
Date date = new Date();
DateFormat.getDateInstance().format(date);
部署到服务器上之后,偶尔会获取到Apr 18, 2022这样的格式,目前还没有找到原因,所以更换为
String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));