小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
在日常开发中,我们会经常遇到日期相关的问题,今天我在这里梳理一下我经常在日期中遇到的一些知识
1.获取当前时间 new Date();
2.获取当前日期的年月日时分秒
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int year = calendar.get(Calendar.YEAR); //获取年份
int month = calendar.get(Calendar.MINUTE); //获取月份
int day = calendar.get(Calendar.DAY_OF_MONTH); //获取日
int hour = calendar.get(Calendar.HOUR_OF_DAY); //获取时
int minute = calendar.get(Calendar.MINUTE); //获取分
int second = calendar.get(Calendar.SECOND); //获取秒
3.对日期进行加减
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.YEAR, -1); //对当前日期加上1年
calendar.add(Calendar.YEAR, -1); //对当前日期减去1年
calendar.add(Calendar.MONTH, 1); //对当前日期加上1月
calendar.add(Calendar.MONTH, -1); //对当前日期减上1月
calendar.add(Calendar.DATE, 1); //对当前日期加上1天
calendar.add(Calendar.DATE, -1); //对当前日期减上1天
对于加减时分秒也是同样的 知识选择的类型不同即可
4.判断两个日期的大小
Date date1 = new Date();
Date date2 = new Date();
date1.after(date2); //判断date1 是否时在 date2 之后
date1.before(date2); //判断date1是否在date2之前
5.根据日期判断年龄
Calendar now = Calendar.getInstance();
now.setTime(new Date()); // 当前时间
Calendar birth = Calendar.getInstance();
birth.setTime(birthday); //生日时间
int age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR); //计算整岁
if (now.get(Calendar.MONTH) <= birth.get(Calendar.MONTH)) {
if (now.get(Calendar.MONTH) == birth.get(Calendar.MONTH)) {
if (now.get(Calendar.DAY_OF_MONTH) < birth.get(Calendar.DAY_OF_MONTH)) {
age--; //当前日期在生日之前,年龄减一
}
} else {
age--; //当前月份在生日之前,年龄减一
}
}
6.根据日期判断时星期几
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1 //注意这里要减1
7.日期格式化
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前系统日期 类型可以按自己的需要来设置
String date = df.format(date);
以上这些是我在开发中会使用到的一些关于日期的方法,如果还有其他的方法 比较好用的 欢迎在评论区评论