package com.cary.util;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* 日期时间辅助工具类
*
* @author cary.liu
* @date 2013-11-6
*/
public class DateTimeUtil {
// 默认时间格式
static final String FORMAT_DATETIME_DEFAULT = "yyyy-MM-dd HH:mm:ss";
// 时间格式没有秒
static final String FORMAT_DATETIME_NO_SECHODE = "yyyy-MM-dd HH:mm";
// 日期默认格式
static final String FORMAT_DATE_DEFAULT = "yyyy-MM-dd";
// 日期格式没有分隔符
static final String FORMAT_DATE_NO_SEPARATOR = "yyyyMMdd";
static final String FORMAT_YEAR_MONTH = "yyyyMM";
/**
* 获取当前时间(默认格式)
*
* @return
* @author cary.liu
*/
public static String getCurrentDateTimeString() {
Date date = new Date();
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_DATETIME_DEFAULT);
return dateformat.format(date);
}
/**
* 获取当前的年和月
*
* @return
* @author cary.liu
*/
public static String getCurrentYearMonth() {
Date date = new Date();
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_YEAR_MONTH);
return dateformat.format(date);
}
/**
* 根据年月获得日期
*
* @param year
* @param month
* @return
* @author cary.liu
*/
public static Date yearMonth2Date(String year, String month) {
if (isEmpay(year) || isEmpay(month)) {
return null;
}
Integer _month = Integer.valueOf(month);
if (_month < 0 || _month > 12) {
return null;
}
String dateStr = year + month;
Date date = null;
SimpleDateFormat format = new SimpleDateFormat(FORMAT_YEAR_MONTH);
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
format.setTimeZone(gmtTime);
try {
if (dateStr == null || "".equals(dateStr)) {
return null;
}
date = format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
return date;
}
/**
* 获取当前时间(指定格式)
*
* @param formatStr
* @return
* @author cary.liu
*/
public static String getCurrentDateTimeString(String formatStr) {
Date date = new Date();
SimpleDateFormat formater = null;
if (formatStr == null || "".equals("")) {
formater = new SimpleDateFormat(FORMAT_DATETIME_DEFAULT);
} else {
formater = new SimpleDateFormat(formatStr);
}
return formater.format(date);
}
/**
* 获取当前日期
*
* @return
* @author cary.liu
*/
public static String getCurrentDay() {
Date date = new Date();
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_DATE_DEFAULT);
return dateformat.format(date);
}
/**
* 获取当前时间的相差时间
*
* @param hours 相差时间(单位h)
* @return
*/
public static String timeMinus(String hours) {
if ("".equals(String.valueOf(hours)))
return "";
Calendar cl = Calendar.getInstance();
Long time = cl.getTimeInMillis() - Double.valueOf(Double.valueOf(hours) * 60 * 60 * 1000).longValue();
cl.setTimeInMillis(time);
Date date = cl.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_DATETIME_DEFAULT);
return dateformat.format(date);
}
/**
* 返回两个日期相差的天数
*
* @param startDate
* @param endDate
* @return
*/
public static long getDifferDays(Date startDate, Date endDate) {
long totalDate = 0;
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
long timestart = calendar.getTimeInMillis();
calendar.setTime(endDate);
long timeend = calendar.getTimeInMillis();
totalDate = Math.abs((timeend - timestart)) / (1000 * 60 * 60 * 24);
return totalDate;
}
/**
* 返回当前日期
*
* @return
* @create 2012-8-31 上午09:18:35
*/
public static String getCurrentDateString() {
Date date = new Date();
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_DATE_DEFAULT);
return dateformat.format(date);
}
/**
* 获取多少天后的日期
*
* @param day
* @return
* @author cary.liu
*/
public static String getRelativeDateString(int day) {
Date myDate = new Date();
long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * day;
myDate.setTime(myTime * 1000);
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_DATE_DEFAULT);
return dateformat.format(myDate);
}
/**
* 日期相加
*
* @param today
* @param day
* @return
* @author cary.liu
*/
public static String getRelativeDateString(String today, int day) {
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_DATE_DEFAULT);
Date myDate = null;
try {
myDate = dateformat.parse(today);
} catch (Exception e) {
e.printStackTrace();
return today;
}
long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * day;
myDate.setTime(myTime * 1000);
return dateformat.format(myDate);
}
/**
* 根据日期起,获得会计区间的日期止
*
* @param fsrqq
* @return
*/
public static String getKjqj(String fsrqq) {
String ret = fsrqq;
String year = fsrqq.substring(0, 4);
String month = fsrqq.substring(5, 7);
if (Integer.parseInt(month) == 12)
ret = String.valueOf(Integer.parseInt(year) + 1) + "-01-01";
else {
month = "00" + String.valueOf(Integer.parseInt(month) + 1);
month = month.substring(month.length() - 2, month.length());
ret = year + "-" + month + "-01";
}
return getRelativeDateString(ret, -1);
}
/**
* 获取当前时间戳
*
* @return
* @author cary.liu
*/
public static Timestamp getCurrentDateTime() {
return dateToDateTime(new Date());
}
public static Timestamp dateToDateTime(Date d) {
return strToDateTime(String.valueOf(d));
}
/**
* 蒋字符串转换为时间戳
*
* @param strArg
* @return
* @author cary.liu
*/
public static Timestamp strToDateTime(String strArg) {
if (strArg.equals(null) || strArg.trim().length() < 8)
strArg = "19010101";
if (strArg.indexOf("-") <= 0) {
strArg = strArg.substring(0, 4) + "-" + strArg.substring(4, 6) + "-" + strArg.substring(6, 8);
}
try {
Timestamp nret = Timestamp.valueOf(strArg + " 00:00:00.000000000");
return nret;
} catch (NumberFormatException e) {
return Timestamp.valueOf("1901-01-01 00:00:00.000000000");
}
}
public static Timestamp fullStrToTime(String strArg) {
try {
Timestamp nret = Timestamp.valueOf(strArg);
return nret;
} catch (NumberFormatException e) {
return Timestamp.valueOf("1901-01-01 00:00:00.000000000");
}
}
/**
* 获取这个月有多少天
*
* @return
* @author cary.liu
*/
public static String getFirstDayOfThisMonth() {
String ts = getCurrentDateString();
int nYear = Integer.parseInt(ts.substring(0, 4));
int nMonth = Integer.parseInt(ts.substring(5, 7));
String strResult = String.valueOf(nYear);
if (nMonth < 10) {
strResult += "-0" + String.valueOf(nMonth);
} else {
strResult += "-" + String.valueOf(nMonth);
}
return strResult + "-" + "01";
}
/**
* 获取最后一个月有多少天
*
* @return
*/
public static String getFirstDayOfLastMonth() {
String ts = getCurrentDateString();
int nYear = Integer.parseInt(ts.substring(0, 4));
int nMonth = Integer.parseInt(ts.substring(5, 7));
if (nMonth == 1) {
nYear = nYear - 1;
nMonth = 1;
} else
nMonth -= 1;
String strResult = String.valueOf(nYear);
if (nMonth < 10) {
strResult += "-0" + String.valueOf(nMonth);
} else {
strResult += "-" + String.valueOf(nMonth);
}
return strResult + "-" + "01";
}
public static String getLastDayOfLastMonth() {
String s = getFirstDayOfThisMonth();
return getRelativeDateString(s, -1);
}
/**
* 时间相加多少小时
*
* @param day
* @param x
* @return
*/
public static String addDateHour(String day, int x) {
SimpleDateFormat format = new SimpleDateFormat(FORMAT_DATETIME_NO_SECHODE);// 24小时制
Date date = null;
try {
date = format.parse(day);
} catch (Exception ex) {
ex.printStackTrace();
}
if (date == null)
return "";
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DECEMBER, x);// 24小时制
date = cal.getTime();
cal = null;
return format.format(date);
}
/**
* 字符串转换为日期
*
* @param dateStr
* @return
*/
public static Date toDate(String dateStr) {
SimpleDateFormat dateformat = new SimpleDateFormat(FORMAT_DATE_DEFAULT);
Date date = null;
try {
if (dateStr == null || "".equals(dateStr)) {
return null;
}
date = dateformat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
return date;
}
/**
* 返回两个日期相差的分钟
*
* @param startDate
* @param endDate
* @return
*/
public static long getDifferMinute(Date startDate, Date endDate) {
long totalMins = 0;
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
long timestart = calendar.getTimeInMillis();
calendar.setTime(endDate);
long timeend = calendar.getTimeInMillis();
totalMins = Math.abs((timeend - timestart)) / (1000 * 60);
return totalMins;
}
/**
* 返回两个日期相差的秒
*
* @param startDate
* @param endDate
* @return
*/
public static long getDifferSecond(String startDate, String endDate) {
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATETIME_DEFAULT);
Calendar c = Calendar.getInstance();
try {
Date d1 = sdf.parse(startDate);
Date d2 = sdf.parse(endDate);
long l1 = d1.getTime();
long l2 = d2.getTime();
long l = l1 - l2;
Date d = new Date(l);
c.setTime(d);
} catch (ParseException e) {
e.printStackTrace();
}
return (c.getTimeInMillis() / 1000);
}
/**
* 时间格式处理
*
* @param time
* @return
*/
public static String dealTime(String time) {
String str = "";
try {
String df = "HH:mm";
if (time.length() > 5) {
df = "HH:mm:ss";
}
SimpleDateFormat formatter = new SimpleDateFormat(df);
Date date = formatter.parse(time);
str = formatter.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 返回两个相差的分钟
*
* @param startDate
* @param endDate
* @return
*/
public static long getDifferMinute(long startDate, long endDate) {
long totalMins = (endDate - startDate) / 1000 / 60;
return totalMins;
}
/**
* 获取昨天日期
*
* @return
*/
public static String getYesterday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date d = cal.getTime();
SimpleDateFormat sp = new SimpleDateFormat(FORMAT_DATE_DEFAULT);
return sp.format(d);
}
/**
* 获得时间差
*
* @param ms
* @return
*/
public static String getDifferenceTime(long ms) {
int h = 0;
int d = 0;
int s = 0;
long second = ms / 1000;
int temp = (int) (second % 3600);
if (second > 3600) {
h = (int) second / 3600;
if (temp != 0) {
if (temp > 60) {
d = temp / 60;
if (temp % 60 != 0) {
s = temp % 60;
}
} else {
s = temp;
}
}
} else {
d = (int) (second / 60);
if (second % 60 != 0) {
s = (int) (second % 60);
}
}
return h + "h" + " " + d + "m" + " " + s + "s";
}
/**
* 时间加上 days天数
*
* @param days
* @return
*/
public static String currentDateAddDays(int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + days);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(calendar.getTime());
}
/**
* 蒋时间戳转为日期
*
* @param timestampString
* @param formats
* @return
* @author cary.liu
*/
public static String timestamp2Date(Timestamp timestamp) {
if (timestamp == null) {
return "";
}
long time = timestamp.getTime();
String date = new SimpleDateFormat(FORMAT_DATE_DEFAULT).format(new Date(time));
return date;
}
/**
* 获取时间戳的年
*
* @return
* @author cary.liu
*/
public static String getYearByTempstamp(Timestamp timestamp) {
if (timestamp == null) {
return "";
}
String date = timestamp2Date(timestamp);
String year = date.split("-")[0];
return year;
}
/**
* 获取时间戳的月
*
* @return
* @author cary.liu
*/
public static String getMonthByTempstamp(Timestamp timestamp) {
if (timestamp == null) {
return "";
}
String date = timestamp2Date(timestamp);
String month = date.split("-")[1];
if (month == null || month.equals("")) {
return "";
}
if (Integer.valueOf(month) < 10) {
month = month.replace("0", "");
}
return month;
}
/**
* 获取时间戳的日
*
* @return
* @author cary.liu
*/
public static String getDayByTempstamp(Timestamp timestamp) {
if (timestamp == null) {
return "";
}
String date = timestamp2Date(timestamp);
String day = date.split("-")[2];
if (day == null || day.equals("")) {
return "";
}
if (Integer.valueOf(day) < 10) {
day = day.replace("0", "");
}
return day;
}
/**
* 根据年月日字符串获取时间戳
*
* @param year 年份
* @param month 月份
* @param day 日
* @author cary.liu
*/
public static Timestamp getTimestamp(String year, String month, String day) {
if (isEmpay(year) || isEmpay(month) || isEmpay(day)) {
return null;
}
int _month = Integer.valueOf(month);
int _day = Integer.valueOf(day);
if (_month < 10 && month.indexOf("0") < 0) {
month = "0" + month;
}
if (_day < 10 && day.indexOf("0") < 0) {
day = "0" + day;
}
String date = year + "-" + month + "-" + day;
String dateStr = date + " " + "00:" + "00:" + "00";
Timestamp timestamp = Timestamp.valueOf(dateStr);
return timestamp;
}
/**
* 获取当前时间戳
*
* @return
* @author cary.liu
*/
public static Timestamp getCurrentTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
public static boolean isEmpay(String str) {
if (str == null || "".equals("")) {
return false;
}
return true;
}
public static void main(String[] args) throws ParseException {
System.out.println(getDifferSecond("2012-2-13 12:14:12", "2012-2-13 12:13:12"));
System.out.println("getDifferenceTime:" + getDifferenceTime(1333));
System.out.println(getCurrentDateTimeString());
Timestamp time = new Timestamp(System.currentTimeMillis());
System.out.println("时间:" + timestamp2Date(time));
System.out.println("年:" + getYearByTempstamp(time));
System.out.println("月:" + getMonthByTempstamp(time));
System.out.println("日:" + getDayByTempstamp(time));
String year = "2001";
String month = "12";
String day = "5";
Timestamp t = getTimestamp(year, month, day);
System.out.println("timestamp:" + t);
// System.out.println("年月:" + getCurrentYearMonth());
System.out.println("年月:" + yearMonth2Date("1900", "12"));
System.setProperty("user.timezone","Asia/Shanghai");
}
}