欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java学习笔记-Calendar和Date使用

程序员文章站 2022-07-10 17:23:33
1.获取当前时间Calendar cal = Calendar.getInstance();System.out.println(cal.getTime());Date date=new Date();System.out.println(date);输出结果一致:Tue Jan 05 11:18:46 CST 2021Tue Jan 05 11:18:46 CST 20212.获取年月日date.getDay()等其他get年月日的方法已经废弃,当然啦,如果.....

1.获取当前时间

Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());

Date date=new Date();
System.out.println(date);

 

输出结果一致:

Tue Jan 05 11:18:46 CST 2021
Tue Jan 05 11:18:46 CST 2021

 

2.获取年月日

date.getDay()等其他get年月日的方法已经废弃,当然啦,如果非要用,也不是不可以。

但目前都推荐用Calendar去获取年月日

//年
System.out.println(calendar.get(Calendar.YEAR));
//月
System.out.println(calendar.get(Calendar.MONTH));
//日
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
//时
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
//分
System.out.println(calendar.get(Calendar.MINUTE));
//秒
System.out.println(calendar.get(Calendar.SECOND));

 

3.日期格式化

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));

输出如下:

2021-01-05 11:32:44
 

Date date = new Date();
System.out.println(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Date类型转换成 yyyy-MM-dd HH:mm:ss类型
System.out.println(sdf.format(date));

输出如下:

Tue Jan 05 11:33:33 CST 2021
2021-01-05 11:33:33
 

 

4.日期新增xx年/月/日/小时/秒

Date date=new Date();
System.out.println(date);
System.out.println(DateUtils.addDays(date, -7));
System.out.println(DateUtils.addMonths(date, -1));
System.out.println(DateUtils.addHours(date, -1));
System.out.println(DateUtils.addMinutes(date, -1));
System.out.println(DateUtils.addYears(date, -1));

输出如下:

Tue Jan 05 11:36:32 CST 2021
Tue Dec 29 11:36:32 CST 2020
Sat Dec 05 11:36:32 CST 2020
Tue Jan 05 10:36:32 CST 2021
Tue Jan 05 11:35:32 CST 2021
Sun Jan 05 11:36:32 CST 2020

 

Date date = new Date();
System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(date));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
//年
cal.add(Calendar.YEAR, 3);
System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(cal.getTime()));
//天
cal.add(Calendar.DATE, 3);
System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(cal.getTime()));

输出如下:

2021-01-05
2024-01-05
2024-01-08

 

本文地址:https://blog.csdn.net/mumuwang1234/article/details/112219682

相关标签: java