参考:
类的概览 重要解释//实例化 //getInstance()会调用setTimeInMillis(System.currentTimeMillis()); //最终执行 time = millis; (time是cal的protected long time 字段) Calendar cal = Calendar.getInstance(); //或者用这一句,效果一样 cal.setTime(new Date()); // setTimeInMillis(date.getTime()); time = millis; //得到当前年份 // 下面这句的意思是:得到 实例cal里的time字段的值换算为Calendar.YEAR后的值。注意没有改变cal里面的YEAR字段值 int year = cal.get(Calendar.YEAR); System.out.println("现在是" + year + "年");//输出: 现在是2021年 System.out.println("cal是" + cal.YEAR + "年");//输出: cal是1年 cal.YEAR = 20;//报错 //- The final field Calendar.YEAR cannot be assigned //- The static field Calendar.YEAR should be accessed in a创建流水号
精确到毫秒
// 创建流水号 Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1;// 因为月份从0开始,所以加一 int day = cal.get(Calendar.DATE); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); // 获取当前分钟 int second = cal.get(Calendar.SECOND); // 获取当前秒数 int millisecond = cal.get(Calendar.MILLISECOND); // 获取毫秒数 String transSerialNo = "xfrs" + String.format("%04d", year) + String.format("%02d", month) + String.format("%02d", day) + String.format("%02d", hour) + String.format("%02d", minute) + String.format("%03d", millisecond); System.out.println(transSerialNo);
输出xfrs202110191618204
解释一些字段如下:
public final static int YEAR = 1; public final static int MonTH = 2; public final static int WEEK_OF_YEAR = 3; public final static int DATE = 5; protected int fields[]; protected long time;
官方说明:
Like other locale-sensitive classes, Calendar provides a
- class method, getInstance, for getting a generally useful
- object of this type. Calendar’s getInstance method
- returns a Calendar object whose
- calendar fields have been initialized with the current date and time:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)