这几个月工作都很忙, 项目很紧, 导致很长一段时间没有继续更新, 再次做下记录, 巩固一下所用到的知识, 话不多说,先分享一个强大的日期操作工具类:
import com.aiitec.openapi.utils.LogUtil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* author: Alan on 2016/12/8 21:08
* address: xk6321@gmail.com
* description: 常用的日期工具类
*/
public class DateUtil {
private static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String DATE = "yyyy-MM-dd";
private static final String TIME = "HH:mm";
private static final String YEAR = "yyyy";
private static final String MONTH = "MM";
private static final String DAY = "dd";
private static final String HOUR = "HH";
private static final String MINUTE = "mm";
private static final String SEC = "ss";
private static final String DATETIMECHINESE = "yyyy年MM月dd日 HH时mm分ss秒";
private static final String DATECHINESE = "yyyy年MM月dd日";
private static final String SIMPLEDATECHINESE = "MM月dd日";
private static final String SIMPLEDATECHINESES = "MM月dd日 HH:mm:ss";
private static String mWay;
private static String[] constellationArr = {"魔羯座", "水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座"};
private static int[] constellationEdgeDay = {20, 18, 20, 20, 20, 21, 22, 22, 22, 22, 21, 21};
public static Date str2Date(String str) {
return str2Date(str, null);
}
/**
* 字符串转 date
* @param str 时间字符串
* @param format 格式
* @return
*/
public static Date str2Date(String str, String format) {
if (str == null || str.length() == 0) {
return null;
}
if (format == null || format.length() == 0) {
format = FORMAT;
}
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
public static Calendar str2Calendar(String str) {
return str2Calendar(str, null);
}
/**
* 字符串转 Calendar
* @param str
* @param format
* @return
*/
public static Calendar str2Calendar(String str, String format) {
Date date = str2Date(str, format);
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
return c;
}
/**
* date 转换为时间
* @param c
* @return
*/
public static String date2Str(Calendar c) {// yyyy-MM-dd HH:mm:ss
return date2Str(c, null);
}
public static String date2Str(Calendar c, String format) {
if (c == null) {
return null;
}
return date2Str(c.getTime(), format);
}
public static String date2Str(Date d) {// yyyy-MM-dd HH:mm:ss
return date2Str(d, null);
}
public static String date2Str(Date d, String format) {// yyyy-MM-dd HH:mm:ss
if (d == null) {
return null;
}
if (format == null || format.length() == 0) {
format = FORMAT;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
String s = sdf.format(d);
return s;
}
/**
* 转换时间格式
*
* @param time 时间字符串
* @param inFormat 原来的字符串格式
* @param outFotmat 希望输出的字符串格式
* @return
*/
public static String formatStr(String time, String inFormat, String outFotmat) {
return date2Str(str2Date(time, inFormat), outFotmat);
}
/**
* 获得当前日期的字符串格式
*
* @param format 要输出的格式,如 yyyy年MM月dd日
* @return 2017年01月17日
*/
public static String getCurDateStr(String format) {
Calendar c = Calendar.getInstance();
return date2Str(c, format);
}
/**
* 格式到天
*
* @param time
* @return
*/
public static String getDay(long time) {
return new SimpleDateFormat("yyyy-MM-dd").format(time);
}
/**
* 格式到秒
*
* @param time
* @return
*/
public static String getMillon(long time) {
return new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(time);
}
/**
* 格式到毫秒
*
* @param time
* @return
*/
public static String getSMillon(long time) {
return new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(time);
}
/**
* 获取当前是星期几
*
* @return 星期
*/
public static String getCurWeek() {
Calendar c = Calendar.getInstance();
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return "星期" + mWay;
}
/**
* 获取两个日期的相差天数
*/
public static int daysBetween(Date date1, Date date2) throws ParseException {
long time1 = date1.getTime();
long time2 = date2.getTime();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 获取当前是本年的第几周
*/
public static int getCurrentYearWeek() {
Calendar c = Calendar.getInstance();
return c.get(Calendar.WEEK_OF_YEAR);//获取是本年的第几周
}
/**
* 将时间转换为毫秒
*
* @param expireDate
* @return
*/
public static long getSecondsFromDate(String expireDate) {
if (expireDate == null) {
return -1;
}
long timeInMillis = 0;
Calendar c = Calendar.getInstance();
try {
c.setTime(new SimpleDateFormat(FORMAT).parse(expireDate));
timeInMillis = c.getTimeInMillis();
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMillis;
}
/**
* 获取当前时间的毫秒值
*
* @return
*/
public static long getCurSecondsFromDate() {
String curDateStr = getCurDateStr(FORMAT);
long timeInMillis = 0;
Calendar c = Calendar.getInstance();
try {
c.setTime(new SimpleDateFormat(FORMAT).parse(curDateStr));
timeInMillis = c.getTimeInMillis();
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMillis;
}
//秒数转化为日期
public static String getDateFromSeconds(String seconds) {
if (seconds == null)
return " ";
else {
Date date = new Date();
try {
date.setTime(Long.parseLong(seconds) * 1000);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
return "Input string:" + seconds + "not correct,eg:2011-01-20";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
}
//检查输入的日期格式是否正确
public static boolean checkDate(String date) {
String DatePattern = "^(?:([0-9]{4}-(?:(?:0?[1,3-9]|1[0-2])-(?:29|30)|"
+ "((?:0?[13578]|1[02])-31)))|"
+ "([0-9]{4}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|1\\d|2[0-8]))|"
+ "(((?:(\\d\\d(?:0[48]|[2468][048]|[13579][26]))|"
+ "(?:0[48]00|[2468][048]00|[13579][26]00))-0?2-29)))$";
Pattern p = Pattern.compile(DatePattern);
Matcher m = p.matcher(date);
boolean b = m.matches();
return b;
}
/**
* 获取指定时间
*/
public static Long getAfterMonth(int month) {
Calendar cal = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = df.parse("20130304");
} catch (Exception e) {
}
cal.setTime(date);
long timestamp = cal.getTimeInMillis();
return timestamp;
}
/**
* 获取当月份月第一天
*/
public static String getFirstDayOfMonth() {
String str = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1 号
str = sdf.format(lastDate.getTime());
return str;
}
/**
* 获得当月份最后一天
*/
public static String getNextMonthEnd() {
String str = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH, 1);//加一个月
lastDate.set(Calendar.DATE, 1);//把日期设置为当月第一天
lastDate.roll(Calendar.DATE, -1);//日期回滚一天,也就是本月最后一天
str = sdf.format(lastDate.getTime());
return str;
}
/**
* 判断是否是上学期
*
* @return
* @throws ParseException
*/
public static int isLastSemester() throws ParseException {
long nowTimeLong = new Date().getTime();
long ckStartTimeLong = new SimpleDateFormat(FORMAT).parse(getYear() + "-09-01 00:00:00")
.getTime();
long ckOverTimeLong = new SimpleDateFormat(FORMAT).parse(getNextYearFirst() + "-02-" + getLastDayOfMonth(Integer.parseInt(getYear()) + 1, 2) + " 23:59:59")
.getTime();
//如果在这个时间段内,则为上学期
if (nowTimeLong > ckStartTimeLong && nowTimeLong < ckOverTimeLong) {
return 1;
}
return 0;
}
/**
* 判断是否是下学期
*
* @return
* @throws ParseException
*/
public static int isNextSemester()
throws ParseException {
long nowTimeLong = new Date().getTime();
long ckStartTimeLong = new SimpleDateFormat(FORMAT).parse(getYear() + "-03-01 00:00:00")
.getTime();
long ckOverTimeLong = new SimpleDateFormat(FORMAT).parse(getYear() + "-08-31 23:59:59")
.getTime();
//如果在这个时间段内,则为下学期
if (nowTimeLong > ckStartTimeLong && nowTimeLong < ckOverTimeLong) {
return 1;
}
return 0;
}
/**
* 获取当前年
*/
public static String getYear() {
return new SimpleDateFormat(YEAR).format(new Date());
}
/**
* 获取当前月
*
* @return
*/
public static String getMonth() {
return new SimpleDateFormat(MONTH).format(new Date());
}
// 获取当前日
public static String getDay() {
return new SimpleDateFormat(DAY).format(new Date());
}
/**
* 获取当前时
*/
public static String getHour() {
return new SimpleDateFormat(HOUR).format(new Date());
}
/**
* 获取当前分
*/
public static String getMinute() {
return new SimpleDateFormat(MINUTE).format(new Date());
}
/**
* 获取当前秒
*/
public static String getSec() {
return new SimpleDateFormat(SEC).format(new Date());
}
/**
* 获得明年
*/
public static String getNextYearFirst() {
String str = "";
SimpleDateFormat sdf = new SimpleDateFormat(YEAR);
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.YEAR, 1);
str = sdf.format(lastDate.getTime());
return str;
}
/**
* 获取某年某月的最后一天
* @param year 年
* @param month 月
* @return last day
*/
public static int getLastDayOfMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8
|| month == 10 || month == 12) {
return 31;
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
if (month == 2) {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
return 0;
}
/**
* 是否闰年
*/
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
/**
* 获取学期
*
* @return
*/
public static String getSemester() {
Calendar calendar = Calendar.getInstance();
int mouth = calendar.get(Calendar.MONTH);
if (mouth >= 8) {//9月份以后,
// return calendar.get(Calendar.YEAR)+"年上学期";
return "上学期";
} else if (mouth < 2) { //3月份以前
return "上学期";
} else {
// return calendar.get(Calendar.YEAR)+"年下学期";
return "下学期";
}
}
/**
* 通过生日获取星座
*
* @param birthday yyyy-MM-dd
* @return
*/
public static String getStar(String birthday) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(birthday);
return com.aiitec.qway.utils.DateUtil.getStar(date.getMonth() + 1, date.getDate());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String getStar(int m, int d) {
int month = m;
int day = d;
if (day <= constellationEdgeDay[month - 1]) {
month = month - 1;
}
if (month >= 0) {
return constellationArr[month];
}
//default to return 魔羯
return constellationArr[11];
}
/**
* 通过生日转换成年龄
*
* @param birthday yyyy-MM-dd
* @return 18
*/
public static int getAge(String birthday) {
LogUtil.e("birthday: " + birthday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(birthday);
return new Date().getYear() - date.getYear();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取相差天数
*
* @param birthday 生日 yyyy-MM-dd
* @return
*/
public static long getDifference(String birthday) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(birthday);
return Math.abs(new Date().getTime() - date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取年龄
* @param year
* @return
*/
public static int getAge(int year) {
LogUtil.e("getYear: " + getYear());
LogUtil.e("year: " + year);
return (Integer.parseInt(getYear())) - year;
}
/**
* 将毫秒数差值转换成小时数 HH:MM:ss
*
* @param diff
* @return
*/
public static String ms2Str(long diff) {
long hour = diff / 1000 / 60 / 60;
long min = (diff - hour * 1000 * 60 * 60) / 1000 / 60;
long sec = (diff - hour * 1000 * 60 * 60 - min * 1000 * 60) / 1000;
String h = hour < 10 ? "0" + hour : String.valueOf(hour);
String m = min < 10 ? "0" + min : String.valueOf(min);
String s = sec < 10 ? "0" + sec : String.valueOf(sec);
return String.format("%s:%s:%s", h, m, s);
}
/**
* 仿微信的时间格式
*
* @param time yyyy-MM-dd HH:mm:ss
* @return 今天 HH:mm
*/
public static String formatDateTimes(String time) {
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (time == null || "".equals(time)) {
return "";
}
Date date = null;
try {
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar current = Calendar.getInstance();
Calendar today = Calendar.getInstance(); //今天
today.set(Calendar.YEAR, current.get(Calendar.YEAR));
today.set(Calendar.MONTH, current.get(Calendar.MONTH));
today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
// Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
Calendar yesterday = Calendar.getInstance(); //昨天
Calendar aWeekAgoDay = Calendar.getInstance();//一周前
//一天前(昨天)
yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
yesterday.set(Calendar.HOUR_OF_DAY, 0);
yesterday.set(Calendar.MINUTE, 0);
yesterday.set(Calendar.SECOND, 0);
//一周前
aWeekAgoDay.set(Calendar.YEAR, current.get(Calendar.YEAR));
aWeekAgoDay.set(Calendar.MONTH, current.get(Calendar.MONTH));
aWeekAgoDay.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 7);
aWeekAgoDay.set(Calendar.HOUR_OF_DAY, 0);
aWeekAgoDay.set(Calendar.MINUTE, 0);
aWeekAgoDay.set(Calendar.SECOND, 0);
current.setTime(date);
if (current.after(today)) {
return "今天 " + time.split(" ")[1];
} else if (current.before(today) && current.after(yesterday)) {
return "昨天 ";
} else if (current.before(yesterday) && current.after(aWeekAgoDay)) {
//一周内
int week = current.get(Calendar.DAY_OF_WEEK);
if(week == 1){
return "星期日 ";
}
else if(week == 2){
return "星期一 ";
}
else if(week == 3){
return "星期二 ";
}
else if(week == 4){
return "星期三 ";
}
else if(week == 5){
return "星期四 ";
}
else if(week == 6){
return "星期五 ";
}
else if(week == 7){
return "星期六 ";
}
else {
}
return " ";
} else {
int index = time.indexOf("-") + 1;
return time.substring(index, time.length()).replace("-", "/");
}
}
/**
* 获取时间间隔( 类似于朋友圈的时间 )
*
* @param createtime 传入的时间格式必须类似于2012-8-21 17:53:20 这样的格式
* @return interval
*/
public String getInterval(String createtime) {
String interval = null;
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date d1 = (Date) sd.parse(createtime, pos);
//用现在距离1970年的时间间隔new Date().getTime()减去以前的时间距离1970年的时间间隔d1.getTime()得出的就是以前的时间与现在时间的时间间隔
long time = new Date().getTime() - d1.getTime();// 得出的时间间隔是毫秒
if (time / 1000 < 10 && time / 1000 >= 0) {
//如果时间间隔小于10秒则显示“刚刚”time/10得出的时间间隔的单位是秒
interval = "刚刚";
} else if (time / 3600000 < 24 && time / 3600000 >= 0) {
//如果时间间隔小于24小时则显示多少小时前
int h = (int) (time / 3600000);//得出的时间间隔的单位是小时
interval = h + "小时前";
} else if (time / 60000 < 60 && time / 60000 > 0) {
//如果时间间隔小于60分钟则显示多少分钟前
int m = (int) ((time % 3600000) / 60000);//得出的时间间隔的单位是分钟
interval = m + "分钟前";
} else if (time / 1000 < 60 && time / 1000 > 0) {
//如果时间间隔小于60秒则显示多少秒前
int se = (int) ((time % 60000) / 1000);
interval = se + "秒前";
} else {
//大于24小时,则显示正常的时间,但是不显示秒
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
ParsePosition pos2 = new ParsePosition(0);
Date d2 = (Date) sdf.parse(createtime, pos2);
interval = sdf.format(d2);
}
return interval;
}
/**
* 判断是否是下午
*
* @param timestamp: yyyy-MM-dd HH:mm:ss
* @return AM: 上午 PM: 下午
*/
public static String isAfternoon(String timestamp) {
String time = timestamp.split(" ")[1];
long nowTimeLong = 0;
long ckStartTimeLong = 0;
long ckOverTimeLong = 0;
try {
nowTimeLong = new SimpleDateFormat(FORMAT).parse(getCurDateStr("yyyy-MM-dd ") + time).getTime();
ckStartTimeLong = new SimpleDateFormat(FORMAT).parse(getCurDateStr("yyyy-MM-dd") + " 12:00:00")
.getTime();
ckOverTimeLong = new SimpleDateFormat(FORMAT).parse(getCurDateStr("yyyy-MM-dd") + " 23:59:59")
.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
//如果在这个时间段内,则为下午
if (nowTimeLong > ckStartTimeLong && nowTimeLong < ckOverTimeLong) {
return "PM";
}
return "AM";
}
}