将字符串转化为目标格式的日期
首先 需求:给你看的这列不是日期加时间么,能不能让里面的时间随机生成在00-15之间(比如9.00就是2021-07-12 9.01.00.000-2021-07-12 9.15.00.000)
分析:只是分钟在00-15之间 可以设置成随机数0-15之间,Math.random()*15+1再取整就可以达到0-15之间的整数,再将其转化为字符串,小于10的再加个0就可
以达到00-15之间。
1 package utils; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 public class a { 8 public static void main(String[] args) throws ParseException { 9 for (int i=0;i<10;i++){ 10 long s1=Math.round(Math.random()*15+1); 11 String ss= String.valueOf(s1); 12 if (Integer.parseInt(ss)<10){ 13 ss="0"+ss; 14 } 15 //region 字符串转换为日期 Wed Dec 12 12:12:12 CST 2012 16 String str1="2021-07-12 9:"+ss+":00:00"; 17 SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 18 Date d1=sdf1.parse(str1); 19 //endregion 20 SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd H:mm:00.000"); 21 String s=sdf2.format(d1); 22 System.out.println(s); 23 24 } 25 }}
输出结果:
2021-07-12 9:12:00.000
2021-07-12 9:01:00.000
2021-07-12 9:13:00.000
2021-07-12 9:06:00.000
2021-07-12 9:09:00.000
2021-07-12 9:03:00.000
2021-07-12 9:06:00.000
2021-07-12 9:04:00.000
2021-07-12 9:15:00.000
2021-07-12 9:03:00.000
浙公网安备 33010602011771号