时间格式化工具类:
这个工具类稍微有点杂,有需要的盆友可以再次封装
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.util.Log;
/**
* 时间解析工具
*
*/
public class DateTimeHelper {
private static final String TAG = "DateTimeHelper";
private static final DateFormat NOW_TIME_FORMATTER_YMDHMS = new SimpleDateFormat(
"yyyyMMddHHmmss"); //20150324123456
private static final DateFormat NOW_TIME_FORMATTER1 = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss"); //2015-12-23 10:23:34
private static final DateFormat NOW_DATA_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd"); //2015-12-23
private static final DateFormat YEAR_AND_MONTH_FORMATTER = new SimpleDateFormat(
"yyyy年MM月"); // 2016年03月
private static final DateFormat NOW_TIME_FORMATTER = new SimpleDateFormat(
"HH:mm:ss", Locale.US); // 10:23:34
/**
* 12:23:43 时分秒
* @param date
* @return
*/
public static final String getTime(Date date) {
return NOW_TIME_FORMATTER.format(date);
}
/**
* 以时间生成的字符串
* @return yyyyMMddHHmmss
*/
public static String getNowYmdhms(){
return NOW_TIME_FORMATTER_YMDHMS.format(new Date());
}
/**
* string生成date
* @param dateString
* @return Date "yyyy-MM-dd HH:mm:ss"
*/
public static Date strToDate(String dateString) {
try {
return NOW_TIME_FORMATTER1.parse(dateString);
} catch (ParseException e) {
Log.e(TAG, "Could not parse Twitter date string: " + e.getMessage().toString());
return null;
}
}
/**
* String生成date
* @param dateString
* @return Date "yyyy-MM-dd"
*/
public static Date detaileDate(String dateString) {
try {
return NOW_DATA_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
/**
* 当前时间转化成"yyyy-MM-dd"字符串
* @return "yyyy-MM-dd"
*/
public static String currentData() {
return NOW_DATA_FORMATTER.format(Calendar.getInstance().getTime());
}
/**
* 当前时间转化成"yyyy-MM-dd HH:mm:ss"字符串
* @return "yyyy-MM-dd HH:mm:ss"
*/
public static String currentTime() {
return NOW_TIME_FORMATTER1.format(Calendar.getInstance().getTime());
}
/**
* Date转化成"yyyy-MM-dd"字符串
* @param d
* @return "yyyy-MM-dd"
*/
public static String currentDataFormatYearAndMonth(Date d) {
if(d==null)
return "";
return NOW_DATA_FORMATTER.format(d);
}
/**
* 返回前一天时间字符串
* @return 前一天时间 "yyyy-MM-dd"
*/
public static String getYesterday(){
String yesterday = "";
Date d=new Date(System.currentTimeMillis()-1000*60*60*24);
SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd");
yesterday =sp.format(d);//获取昨天日期
return yesterday;
}
/**
* 将json格式时间字符转换成时间对象
*
* @param json
* @return
*/
public static Date getJsonDate(String json) {
if (json.equals("")) {
return new Date(0);
}
String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
Matcher matcher = pattern.matcher(json);
String result = matcher.replaceAll("$2");
return new Date(Long.valueOf(result));
}
/**
* Date to string
* @param date
* @return
*/
public static String toJsonDate(Date date) {
String JSONDateToMilliseconds = "/Date("
+ String.valueOf(date.getTime()) + ")/";
return JSONDateToMilliseconds;
}
//----------------------------------------------------------------------
/**
* 得到对应日期的对应显示格式的文本串 当天内的:
* 1小时内的,直接显示多少分钟前;
* 1小时外的,显示上午 ,下午
* 昨天的:直接显示昨天上下午或晚上
* 前天的:直接显示前天上下午或晚上
* 上本周的:直接显示上周几
* 本周的:直接显示周几
* 大于一周的:直接显示日期
*
* @param date
* @return
*/
public static String getShowFormatDate(Date date) {
String showDateTime;
Calendar now = Calendar.getInstance();
Calendar target = Calendar.getInstance();
target.setTime(date);
if (isSameDay(now, target)) {
int intervalHour = getIntervalHour(now, target);
if (intervalHour >= 0 && intervalHour < 1) {
int minute = getIntervalMinute(now, target);
showDateTime = minute > 0 ? minute + "分钟前" : "刚刚";
} else if (intervalHour < 0) {
intervalHour = Math.abs(intervalHour);
showDateTime = intervalHour + "小时前";
} else {
showDateTime = timeToTimeRange(target);
}
} else if (isSameYear(now, target)) {
int intervalDay = getIntervalDay(now, target);
if (intervalDay == 1) {
showDateTime = "昨天" + timeToTimeRange(target);
} else if (intervalDay > 1 && intervalDay <= 7) {
boolean isSameWeek = isSameWeekWithToday(date);
if (isSameWeek)
showDateTime = dayForWeek(target);
else {
showDateTime = "上" + dayForWeek(target);
}
} else if (intervalDay == -1) {
showDateTime = "明天" + timeToTimeRange(target);
} else if (intervalDay == -2) {
showDateTime = "后天" + timeToTimeRange(target);
} else {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
showDateTime = sdf.format(target.getTime());
}
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
showDateTime = sdf.format(target.getTime());
}
return showDateTime;
}
/**
* 时间转换为时间段,例:09:00-12:00 转换为上午
*
* @return 时间段
*/
private static String timeToTimeRange(Calendar c) {
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return getRange(hour, minute);
}
/**
* 根据小时和分钟确定时间段
*
* @param hour
* 小时
* @param minute
* 分钟
* @return 时间段 字符串 (凌晨 上午。。。)
*/
private static String getRange(int hour, int minute) {
if ((hour >= 0 && hour <= 4) || (hour == 5 && minute == 0)) {
return "凌晨";
} else if ((hour >= 5 && hour <= 11) || (hour == 12 && minute == 0)) {
return "上午";
} else if (hour >= 12 && hour <= 13) {
return "中午";
} else if (hour >= 14 && hour <= 17) {
return "下午";
} else if (hour >= 18 && hour <= 23) {
return "晚上";
} else {
return "";
}
}
/**
* 判断是否为同一天
* @param cal1
* @param cal2
* @return
*/
private static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("日期不能为空");
}
return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
&& cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1
.get(Calendar.DAY_OF_YEAR) == cal2
.get(Calendar.DAY_OF_YEAR));
}
//-------------------------------------------------------------
/**
* 得到对应日期的对应显示格式的文本串 当天内的:1小时内的,直接显示多少分钟前;1小时外的,直接显示多少小时前 昨天的:直接显示昨天的上下午或晚上
* 本周的:直接显示周几的上下午或晚上 大于一周的:直接显示日期
*
* @param date
* @return
*/
/* public static String getShowFormatDateTime(Date date) {
String showDateTime;
Calendar now = Calendar.getInstance();
Calendar target = Calendar.getInstance();
target.setTime(date);
if (isSameDay(now, target)) {
int intervalHour = getIntervalHour(now, target);
if (intervalHour >= 0 && intervalHour < 1) {
int minute = getIntervalMinute(now, target);
showDateTime = minute > 0 ? minute + "分钟前" : "刚刚";
} else if (intervalHour < 0) {
intervalHour = Math.abs(intervalHour);
showDateTime = intervalHour + "小时前";
} else {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
showDateTime = sdf.format(target.getTime());
showDateTime = timeToTimeRange(target) + " "
+ sdf.format(target.getTime());
}
} else if (isSameYear(now, target)) {
int intervalDay = getIntervalDay(now, target);
if (intervalDay == 1) {
showDateTime = "昨天" + timeToTimeRange(target);
} else if (intervalDay > 1 && intervalDay <= 7) {
boolean isSameWeek = isSameWeekWithToday(date);
if (isSameWeek)
showDateTime = dayForWeek(target) + timeToTimeRange(target);
else {
showDateTime = "上" + dayForWeek(target)
+ timeToTimeRange(target);
}
} else if (intervalDay == -1) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
showDateTime = sdf.format(target.getTime());
showDateTime = "明天" + timeToTimeRange(target) + " "
+ sdf.format(target.getTime());
} else if (intervalDay == -2) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
showDateTime = sdf.format(target.getTime());
showDateTime = "后天" + timeToTimeRange(target) + " "
+ sdf.format(target.getTime());
} else {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
showDateTime = sdf.format(target.getTime());
}
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
showDateTime = sdf.format(target.getTime());
}
return showDateTime;
}*/
/**
* <pre>
* 判断date和当前日期是否在同一周内
* 注:
* Calendar类提供了一个获取日期在所属年份中是第几周的方法,对于上一年末的某一天
* 和新年初的某一天在同一周内也一样可以处理,例如2012-12-31和2013-01-01虽然在
* 不同的年份中,但是使用此方法依然判断二者属于同一周内
* </pre>
*
* @param date
* @return
*/
public static boolean isSameWeekWithToday(Date date) {
if (date == null) {
return false;
}
// 0.先把Date类型的对象转换Calendar类型的对象
Calendar todayCal = Calendar.getInstance();
Calendar dateCal = Calendar.getInstance();
todayCal.setTime(new Date());
dateCal.setTime(date);
// 1.比较当前日期在年份中的周数是否相同
if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal
.get(Calendar.WEEK_OF_YEAR)) {
return true;
} else {
return false;
}
}
/**
* 判断是否为同一年
* @param cal1
* @param cal2
* @return
*/
private static boolean isSameYear(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("日期不能为空");
}
return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR));
}
/**
* 同一天相差多少
* @param cal1
* @param cal2
* @return int
*/
private static int getIntervalDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("日期不能为空");
}
if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
return cal1.get(Calendar.DAY_OF_YEAR)
- cal2.get(Calendar.DAY_OF_YEAR);
} else {
throw new IllegalArgumentException("跨年不能进行比较");
}
}
/**
* 同一个小时内相差多少
* @param cal1
* @param cal2
* @return int
*/
private static int getIntervalHour(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("日期不能为空");
}
if (isSameDay(cal1, cal2)) {
return cal1.get(Calendar.HOUR_OF_DAY)
- cal2.get(Calendar.HOUR_OF_DAY);
} else {
throw new IllegalArgumentException("跨天不能进行比较");
}
}
/**
* 一分钟内相差多少
* @param cal1
* @param cal2
* @return int
*/
private static int getIntervalMinute(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("日期不能为空");
}
if (isSameDay(cal1, cal2)) {
return cal1.get(Calendar.MINUTE) - cal2.get(Calendar.MINUTE);
} else {
throw new IllegalArgumentException("跨天不能进行比较");
}
}
/**
* 相差多少天
* @param startCal
* @param endCal
* @return
*/
public static int countDay(Calendar startCal, Calendar endCal) {
long endTimeInMillis = endCal.getTimeInMillis();
long startTimeInMillis = startCal.getTimeInMillis();
long dayCount = (endTimeInMillis - startTimeInMillis)
/ (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(dayCount));
}
/**
* 返回当前日期的星期
*
* @return string 星期
*/
private static String dayForWeek(Calendar c) {
final String dayNames[] = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
int day = c.get(Calendar.DAY_OF_WEEK) - 1;
return dayNames[day];
}
/**
* 将带时间格式的生日,转换成只有日期的格式
* 2015-12-23 10:23:45 ----> 2015-12-23
* @param birthday
* @return
*/
public static String formatDate(String time) {
String newTime = null;
if (time != null && time.length() >= 10) {
newTime = time.substring(0, 19);
} else {
newTime = time;
}
return newTime;
}
/**
* 获取当前所在周的最后一天的日期
* @return string
*/
public static String getCurrentWeakLastDate() {
String WeakLastDate ="";
Calendar cal = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
System.out.println(df.format(cal.getTime()));
// 这种输出的是上个星期周日的日期,因为老外那边把周日当成第一天
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// 增加一个星期,才是我们中国人理解的本周日的日期
cal.add(Calendar.WEEK_OF_YEAR, 1);
WeakLastDate = df.format(cal.getTime());
return WeakLastDate;
}
/**
* 指定时间与当前时间相差值
* @param Date
* @return long
*/
public static long getDataGap(Date d1){
Date d2 = new Date();
long diff = d1.getTime() - d2.getTime() ;
return diff;
}
/**
* 当前是一天内的第几个小时
* @return int
*/
public static int getCurrentHour(){
int hour = 0 ;
Calendar cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
return hour;
}
/**
* 判断日期格式和范围
* @param String dateStr
* @return boolean
*/
public static boolean isDate(String dateStr) {
String rexp = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?"
+ "((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?" +
"((0?[1-9])|(1[0-9])|(2[0-8]))))))";
Pattern pat = Pattern.compile(rexp);
Matcher mat = pat.matcher(dateStr);
boolean dateType = mat.matches();
return dateType;
}
/**
* 根据出生日期计算 星座
* @param String date
* @return string
*/
public static String star(String date) {
String star="";
String []mdate=date.split("-");
int month=Integer.parseInt(mdate[1]);
int day=Integer.parseInt(mdate[2]);
if (month == 1 && day >= 20 || month == 2 && day <= 18) {
star = "水瓶座";
}
if (month == 2 && day >= 19 || month == 3 && day <= 20) {
star = "双鱼座";
}
if (month == 3 && day >= 21 || month == 4 && day <= 19) {
star = "白羊座";
}
if (month == 4 && day >= 20 || month == 5 && day <= 20) {
star = "金牛座";
}
if (month == 5 && day >= 21 || month == 6 && day <= 21) {
star = "双子座";
}
if (month == 6 && day >= 22 || month == 7 && day <= 22) {
star = "巨蟹座";
}
if (month == 7 && day >= 23 || month == 8 && day <= 22) {
star = "狮子座";
}
if (month == 8 && day >= 23 || month == 9 && day <= 22) {
star = "处女座";
}
if (month == 9 && day >= 23 || month == 10 && day <= 22) {
star = "天秤座";
}
if (month == 10 && day >= 23 || month == 11 && day <= 21) {
star = "天蝎座";
}
if (month == 11 && day >= 22 || month == 12 && day <= 21) {
star = "射手座";
}
if (month == 12 && day >= 22 || month == 1 && day <= 19) {
star = "摩羯座";
}
return star;
}
/**
* 根据用户生日计算年龄
* @param String birth
* @return
*/
public static int getAgeByBirthday(String birth) {
Date birthday=detaileDate(birth);
Calendar cal = Calendar.getInstance();
if (cal.before(birthday)) {
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthday);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH) + 1;
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
// monthNow==monthBirth
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
// monthNow>monthBirth
age--;
}
}
return age;
}
}