字符串与时间的格式转换
这里可以使用hutool的DateUtil进行转换,支持多种格式的时间进行转换
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
String str = "2023/1/6";
String str1 = "2023/01/06";
String str2 = "2023-1-6";
String str3 = "2023-01-06";
String str4 = "2023/1/6 10:00:00";
String str5 = "2023/01/06 10:00:00";
String str6 = "2023-1-6 6:6:6";
String str7 = "2023-01-06 10:00:00";
DateTime parse = DateUtil.parse(str);
DateTime parse1 = DateUtil.parse(str1);
DateTime parse2 = DateUtil.parse(str2);
DateTime parse3 = DateUtil.parse(str3);
DateTime parse4 = DateUtil.parse(str4);
DateTime parse5 = DateUtil.parse(str5);
DateTime parse6 = DateUtil.parse(str6);
DateTime parse7 = DateUtil.parse(str7);
System.out.println(str+"转换成时间后:"+parse);//2023-01-06 00:00:00
System.out.println(str1+"转换成时间后:"+parse1);//2023-01-06 00:00:00
System.out.println(str2+"转换成时间后:"+parse2);//2023-01-06 00:00:00
System.out.println(str3+"转换成时间后:"+parse3);//2023-01-06 00:00:00
System.out.println(str4+"转换成时间后:"+parse4);//2023-01-06 10:00:00
System.out.println(str5+"转换成时间后:"+parse5);//2023-01-06 10:00:00
System.out.println(str6+"转换成时间后:"+parse6);//2023-01-06 06:06:06
System.out.println(str7+"转换成时间后:"+parse7);//2023-01-06 10:00:00
输出:
2023/1/6转换成时间后:2023-01-06 00:00:00
2023/01/06转换成时间后:2023-01-06 00:00:00
2023-1-6转换成时间后:2023-01-06 00:00:00
2023-01-06转换成时间后:2023-01-06 00:00:00
2023/1/6 10:00:00转换成时间后:2023-01-06 10:00:00
2023/01/06 10:00:00转换成时间后:2023-01-06 10:00:00
2023-1-6 6:6:6转换成时间后:2023-01-06 06:06:06
2023-01-06 10:00:00转换成时间后:2023-01-06 10:00:00
通过DateUtil转换之后,格式为:年-月-日 时:分:秒
时间转字符串
String str = "2023/1/6";
//字符串转时间
DateTime parse = DateUtil.parse(str);
System.out.println("parse:"+parse);
//时间转字符串
String s = parse.toDateStr();
System.out.println("parse.toDateStr():"+ s);
输出:
parse:2023-01-06 00:00:00
parse.toDateStr():2023-01-06
获取时间
这里主要使用也是hutool的DateUtil
-
当前时间
String DateUtildate = DateUtil.date().toDateStr(); System.out.println(DateUtildate);//2023-01-10 String DateUtilnow = DateUtil.now(); System.out.println(DateUtilnow);//2023-01-10 14:24:36
-
前n天时间
String startDate = DateUtil.offsetDay(DateUtil.date(),-1).toDateStr();//获取前一天 System.out.println(startDate);//2023-01-09
-
后n天时间
String endDate = DateUtil.offsetDay(DateUtil.date(),3).toDateStr();//获取后三天 System.out.println(endDate);//2023-01-13