身为一名程序员,少不了要对时间、日期做一些比较、转换等等的处理,和根据一定的时间条件对数据库进行查询操作,每次遇到这样的问题的时候大部分都会去百度然后找一些符合需求的文章进来张贴复制使用,当然有一些用的多了也就自己记着了,但是觉得还是有必要总结一下。
0 0可能是太基础了吧,BOSS知道我最近在写技术文章,问了问内容,他让我以后写一些提高点的,别老写基础,不管先把这个总结了。
一、Java时间的转换、比较与日历的应用
Date的基本使用
//获取Date
Date date = new Date();
//也可以从Calendar中获取Date
Calendar calendar = Calendar.getIntance();
Date date = calendar.getTime();
//获取时间戳(当前时间) 1534143874090
//方式一
System.out.println(date.getTime());
//方式二 现在系统一般都推荐用这种方式
System.out.println(System.currentTimeMillis());
//格式化时间
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Date类自带的格式化
DateFormat dateTime = DateFormat.getDateTimeInstance();
DateFormat date = DateFormat.getDateInstance();
//将时间转为格式化字符串
//2018-08-13 11:44:25
System.out.println(timeFormat.format(new Date()));
System.out.println(dateTime.format(new Date()));
//2018-08-13
System.out.println(date.format(new Date()));
System.out.println(dateFormat.format(new Date()));、
//将格式化字符串转为时间
//Mon Aug 13 11:44:25 CST 2018 必须用完整的时间格式
System.out.println(timeFormat.parse("2018-08-13 11:44:25"))
复制代码
Calender的基本使用
上面是时间格式的一些转换,比较简单,但真正烦人的是往往并不是用现在的这个时间,需要去时间进行调整计算,就得用到日历了,设置成指定时间,日期加减、比较等等。
//可以获取当前的日历
Calendar calendar = Calendar.getInstance();
//也可以通过DateFormat获取日历
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = dateFormat.getCalendar();
//直接给日历设置指定时间
calendar.setTime(new Date());
//1年后
calendar.add(Calendar.YEAR, 1);
//1年前
calendar.add(Calendar.YEAR, -1);
//同样的可以替换成Calendar.MONTH,Calendar.DAY_OF_YEAR,Calendar.HOUR等等单位进行替换从而加减
复制代码
Date与Calender的应用
1 最经常的就是计算两个日期中间差了多少天,不多说,来看代码。
public static int getDayDiffer(int beginDay, int endDay) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date beginDate = sdf.parse(String.valueOf(beginDay));
Date endDate = sdf.parse(String.valueOf(endDay));
Calendar cal1 = Calendar.getInstance();
cal1.setTime(beginDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(endDate);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if (year1 != year2) //不一年
{
int timeDistance = 0;
for (int i = year1; i < year2; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) //闰年
{
timeDistance += 366;
} else //不是闰年
{
timeDistance += 365;
}
}
return timeDistance + (day2 - day1);
} else { //同年
return day2 - day1;
}
}
复制代码
2 这是我当时通过传一个指定日子,需要拿他后面一年的所有日期的格式化时间。
public static JSONArray getFormatTimeAllYear(String yyyyMMdd) {
List<String> result = new ArrayList();
result.add(yyyyMMdd);
//+10000等于年的个位数+1
int endYear = Integer.parseInt(yyyyMMdd)+10000;
//如果是当前年就将最后一天设置成当天
if(String.valueOf(yyyyMMdd).startsWith(String.valueOf(calendar.get(Calendar.YEAR)))) {
//getCurrentyyyMMdd()获取天前格式化日期
endYear = getCurrentyyyyMMdd();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date beginDate = new Date();
Date endDate = new Date();
try {
beginDate = sdf.parse(String.valueOf(yyyyMMdd));
endDate = sdf.parse(String.valueOf(endYear));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar begin = Calendar.getInstance();
begin.setTime(beginDate);
//用after方法来判断是否在某日期之后,同有before来判断之前
while (endDate.after(begin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
begin.add(Calendar.DAY_OF_MONTH, 1);
result.add(Integer.valueOf(sdf.format(begin.getTime())));
}
result.remove(result.get(result.size()-1));
return result;
}
public static int getCurrentyyyyMMdd() {
Calendar calenda = Calendar.getInstance();
String year = String.valueOf(calenda.get(Calendar.YEAR));
String mounth = String.valueOf(calenda.get(Calendar.MONTH) + 1);
String day = String.valueOf(calenda.get(Calendar.DAY_OF_MONTH));
if (mounth.length() == 1) {
mounth = "0" + mounth;
}
if (day.length() == 1) {
day = "0" + day;
}
return Integer.valueOf(year + mounth + day);
}
复制代码
3 还有就是经常需要计算某天是周几一类的操作。
//计算某一天是周几
public static int getDayOfWeek(String yyyyMMdd) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date beginDate = new Date();
try {
beginDate = sdf.parse(yyyyMMdd);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(beginDate);
//国外的第一天是从周一开始算的
int day = cal.get(Calendar.DAY_OF_WEEK)-1;
if(day == 0) {
day = 7;
}
return day;
}
//计算某一周是一年中的第几周
public static String getWeekOfYear(String yyyyMMdd) {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
//这一句必须要设置,否则美国认为第一天是周日,而我国认为是周一,对计算当期日期是第几周会有错误
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setTime(df.parse(yyyyMMdd));
return String.valueOf(cal.get(Calendar.WEEK_OF_YEAR));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
复制代码
二、Mysql的时间查询
在使用数据库操作时,也会经常用到按照一定的时间要求来去查询或者进行操作。
1 查询当天的记录
select * from `student` where to_days(create_time) = to_days(now());
复制代码
2 查询当周的记录
//其中的 -insterval 1 day 是因为国外一周从周日开始,这里-1从周一开始计算
select * from `student` where yearweek(date_format(`create_time`, '%y-%m-%d') - interval 1 day) = yearweek(now() - interval 1 day);
复制代码
3 查询上周的记录
select * from `student` where yearweek(date_format(`create_time`, '%y-%m-%d') - interval 1 day) = yearweek(now() - interval 1 day) -1;
复制代码
4 查询7天记录
//根据 interval X day 来调整日期
select * from `student` where date_sub(curdate(), interval 7 day) <= date(`create_time`);
复制代码
5 查询月份记录
// = 0是当月 如果是1则是上个月
select * from `student` where period_diff( date_format( now( ) , '%y%m' ) , date_format(`create_time`, '%y%m' ) ) = 0
复制代码
6 查询季度记录
select * from `student` where QUARTER(`create_time`)= QUARTER(now());
复制代码
7 查询上季度记录
// 根据 interval X QUARTER 来调整季度
select * from `student` where QUARTER(`create_time`)= QUARTER(now(),interval 1 QUARTER));
复制代码
8 查询当年记录
select * from `eco_yunyan_status_history` where YEAR(`create_time`)= YEAR(now());
复制代码
9 查询去年记录
select * from `eco_yunyan_status_history` where YEAR(`create_time`)= YEAR(now()) -1;
复制代码
以上就是总结一些常用的在Java里的时间、日历的使用,以及一些简单的Mysql的时间范围查询,多多指教,互相学习,下次写提高一些的文章。