Java的日期工具类,根据月份获取
package com.ls.testmonth;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 月份的工具类
*/
public class MonthUtils {
/**
* 根据当月获取上个月的第一天和最后一天
*/
public static Map<String, String> getLastMonth(String month) {
Map<String, String> map = new HashMap<String, String>();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//创建一个日历对象
Calendar calendar2 = Calendar.getInstance();
Calendar cale = Calendar.getInstance();
try {
calendar2.setTime(new SimpleDateFormat("yyyy-MM").parse(month));
cale.setTime(new SimpleDateFormat("yyyy-MM").parse(month));
} catch (ParseException e) {
calendar2.setTime(new java.util.Date());
cale.setTime(new java.util.Date());
}
calendar2.add(Calendar.MONTH, -1);
calendar2.set(Calendar.DAY_OF_MONTH, 1);
String startDate = format.format(calendar2.getTime());
cale.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
String endDate = format.format(cale.getTime());
map.put("startDate", startDate);
map.put("endDate", endDate);
return map;
}
/**
* 根据月的开始和和结束,遍历每个月的第一天和最后一天
* @param startMonth
* @param endMonth
* @return
*/
public static List<String> getMonth(String startMonth, String endMonth) {
java.util.Date d1 = null;//定义起始日期
java.util.Date d2 = null;
java.util.Date d3 =null;
Calendar cal = Calendar.getInstance();
try {
d1 = new SimpleDateFormat("yyyy-MM").parse(startMonth);
d2 = new SimpleDateFormat("yyyy-MM").parse(endMonth);
cal.setTime(d2);
cal.add(Calendar.MONTH, +1);
d3 = cal.getTime();
} catch (ParseException e) {
e.printStackTrace();
}//定义起始日期
//定义结束日期
Calendar dd = Calendar.getInstance();//定义日期实例
dd.setTime(d1);//设置日期起始时间
List<String> list = new ArrayList<String>();
while(dd.getTime().before(d3)){//判断是否到结束日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
String str = sdf.format(dd.getTime());
list.add(str);
dd.add(Calendar.MONTH, 1);//进行当前日期月份加1
}
return list;
}
/**
* 根据月获取当前月的第一天和最后一天
* @param month
* @return
*/
public static Map<String, Object> getCurrentMonth(String month) {
Map<String, Object> map= new HashMap<>();
//将时间进行格式化
//创建一个日历对象
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(new SimpleDateFormat("yyyy-MM").parse(month));
} catch (ParseException e) {
calendar.setTime(new java.util.Date());
}
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date startDate = new Date(calendar.getTime().getTime());
calendar.set(Calendar.DAY_OF_MONTH, maxDay);
Date endDate = new Date(calendar.getTime().getTime());
map.put("startDate", startDate);
map.put("endDate", endDate);
return map;
}
}
获取每天指几点的毫秒值
//获取当前时间
long time = System.currentTimeMillis();
//获取每天13点的毫秒值
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long startTime = c.getTimeInMillis();