目录
LocalDateTime -- JDK8 后提供日期时间类(年月日时分秒)
DateTimeFormatter -- JDK8 后提供格式化日期类
ChronoUnit -- JDK8 提供日期时间间隔工具类(推荐)
Date
// 1、创建一个Date类的对象:代表系统此刻日期时间对象
Date d = new Date();
// 2、获取时间毫秒值
long time = d.getTime();
// 1、得到当前时间
Date d1 = new Date();
System.out.println(d1);
// 2、当前时间往后走 1小时 121s
long time2 = System.currentTimeMillis();
time2 += (60 * 60 + 121) * 1000;
// 3、把时间毫秒值转换成对应的日期对象。
Date d2 = new Date(time2);
Date d3 = new Date();
d3.setTime(time2);
SimpleDateFormat
// 1、日期对象
Date d = new Date();
// 2、格式化这个日期对象 (指定最终格式化的形式)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
// 3、开始格式化日期对象成为喜欢的字符串形式
String rs = sdf.format(d);
// 4、格式化时间毫秒值
// 需求:请问121秒后的时间是多少
long time1 = System.currentTimeMillis() + 121 * 1000;
String rs2 = sdf.format(time1);
String dateStr = "2021年08月06日 11:11:11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d2 = sdf.parse(dateStr);
//往后走2天 14小时 49分 06秒
long time = d2.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6) * 1000;
//格式化这个时间毫秒值就是结果
System.out.println(sdf.format(time));
Calendar
// 1、拿到系统此刻日历对象
Calendar cal = Calendar.getInstance();
System.out.println(cal); //可以看到所有Calendar的field
// 2、获取日历的信息:public int get(int field):取日期中的某个字段信息。
int year = cal.get(Calendar.YEAR);
int mm = cal.get(Calendar.MONTH) + 1;
int days = cal.get(Calendar.DAY_OF_YEAR) ;
// 3、public void set(int field,int value):修改日历的某个字段信息。
cal.set(Calendar.HOUR , 12);
// 4.public void add(int field,int amount):为某个字段增加/减少指定的值
// 请问64天后是什么时间
cal.add(Calendar.DAY_OF_YEAR , 64);
cal.add(Calendar.MINUTE , 59);
// 5.public final Date getTime(): 拿到此刻日期对象。
Date d = cal.getTime();
// 6.public long getTimeInMillis(): 拿到此刻时间毫秒值
long time = cal.getTimeInMillis();
LocalDate -- JDK8 后提供日期类(年月日)
// 1、获取本地日期对象。
LocalDate nowDate = LocalDate.now();
System.out.println("今天的日期:" + nowDate);//今天的日期:
int year = nowDate.getYear();
System.out.println("year:" + year);
int month = nowDate.getMonthValue();
System.out.println("month:" + month);
int day = nowDate.getDayOfMonth();
System.out.println("day:" + day);

最低0.47元/天 解锁文章
920

被折叠的 条评论
为什么被折叠?



