直接上代码
Calendar calendar = Calendar.getInstance();
//显示当前时间
System.out.println(calendar.getTime());
//各种日期格式化
SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
String str = format.format(calendar.getTime());
System.out.println(str);
format = new SimpleDateFormat(“yyyyMMdd”);
str = format.format(calendar.getTime());
System.out.println(str);
format = new SimpleDateFormat(“yyyy/MM/dd”);
str = format.format(calendar.getTime());
System.out.println(str);
format = new SimpleDateFormat(“yyyy/M/d”);
str = format.format(calendar.getTime());
System.out.println(str);
//获取时间戳
str = String.valueOf(calendar.getTimeInMillis());
System.out.println(“时间戳: ” + str);
//减去一天
calendar.add(Calendar.DAY_OF_YEAR, -1);
format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
str = format.format(calendar.getTime());
System.out.println(str);
//减去一个月
calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
str = format.format(calendar.getTime());
System.out.println(str);
//减去一年
calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
str = format.format(calendar.getTime());
System.out.println(str);
//只获取日期,不包含时间
calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
str = format.format(calendar.getTime());
System.out.println(str);
//获取本月的第一天
calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
str = format.format(calendar.getTime());
System.out.println(str);
//时间戳字符串转日期时间
calendar = Calendar.getInstance();
str = String.valueOf((calendar.getTimeInMillis() – 60 * 1000) ); //减去一分钟
calendar.setTimeInMillis(Long.parseLong(str));
format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
str = format.format(calendar.getTime());
System.out.println(str);