使用DateUtils处理时间日期转换

3 篇文章 0 订阅
[size=large][b]DateUtils处理时间类[/b][/size]




public class DateUtils {
public static final long ONE_DAY_LONG = 86400000;
private static DateUtils classInstance = new DateUtils();

public static DateUtils getInstance() {
return classInstance;
}


/**
* Timestamp时间类型转换String
* Created on 2014-6-6
* <p>Discription:[]</p>
* @author:[]
* @update:[日期YYYY-MM-DD] [更改人姓名]
* @param time
* @param pattern
* @return String
*/
public static String timestamp2string(Timestamp time, String pattern) {
Date d = new Date(time.getTime());

if (pattern == null) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
return DateFormatUtils.format(d, pattern);
}

/**
* Date时间类型转换String
* Created on 2014-6-6
* 时间格式yyyy-MM-dd HH:mm
* @param date
* @param pattern
* @return String
*/
public static String formatDate(Date date, String pattern) {
if (date == null) {
date = new Date(System.currentTimeMillis());
}

if (pattern == null) {
pattern = "yyyy-MM-dd HH:mm";
}
return DateFormatUtils.format(date, pattern);
}

/**
* date传null获取当前时间
* 时间格式yyyy-MM-dd HH:mm
* Created on 2014-6-6
* @param date
* @return String
*/
public static String defaultFormat(Date date) {
return formatDate(date, null);
}

/**
* 获取当前时间Date类型
* Created on 2014-6-6
* @return Date
*/
public static Date parseDateFormat() {
SimpleDateFormat fo = new SimpleDateFormat();
Date date = new java.util.Date(System.currentTimeMillis());
fo.applyPattern("yyyy-MM-dd");

try {
date = fo.parse(DateFormatUtils.format(date, "yyyy-MM-dd"));
} catch (Exception e) {
}

return date;
}

/**
* 根据Timestamp类型返回2014-06-06格式String
* Created on 2014-6-6
* @param time
* @return String
*/
public static String parseTimestampFormat(Timestamp time) {

if (time != null && !time.equals("")) {

return parseDateFormat(new Date(time.getTime()));

} else {

return "";
}

}

/**
* 根据Date转换String格式yyyy-MM-dd
* Created on 2014-6-6
* @param date
* @return String
*/
public static String parseDateFormat(Date date) {
SimpleDateFormat fo = new SimpleDateFormat();
fo.applyPattern("yyyy-MM-dd");
String retVal = "0000-00-00";
try {
retVal = DateFormatUtils.format(date, "yyyy-MM-dd");
} catch (Exception e) {
}

return retVal;
}

/**
* 根据String返回Timestamp
* Created on 2014-6-6
* @param value
* @return Timestamp
*/
public static Timestamp formatFromYYYYMMDD(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(value);
} catch (ParseException e) {
return null;
}
return new Timestamp(date.getTime());
}

public static Timestamp formatFromYYYYMMDDhhmmss(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(value);
} catch (ParseException e) {
return null;
}
return new Timestamp(date.getTime());
}

public static Date string2Date(String str) {
if (StringUtils.isEmpty(str))
return new Date();
return java.sql.Date.valueOf(str);
}

public static boolean between(Date srcDate, Date startDate, Date endDate) {
if (startDate.after(srcDate))
return false;
if (endDate.before(srcDate))
return false;
return true;
}

public static Date getDayStart(Date date) {
return string2Date(divideDateForDay(date, "yyyy-MM-dd", 0));
// return Timestamp.valueOf(formatDate(date, "yyyy-MM-dd")+" 00:00:00");
}

/**
* 根据传入时间在追加一天
* Created on 2014-6-6
* @param date
* @return
*/
public static Date getDayEnd(Date date) {
return string2Date(divideDateForDay(date, "yyyy-MM-dd", 1));
// return Timestamp.valueOf(formatDate(date, "yyyy-MM-dd")+" 23:59:59");
}

/**
* 给指定时间 追加天数
* Created on 2014-6-6
* @param date
* @param pattern 显示格式
* @param num 需要加的天数
* @return
*/
public static String divideDateForDay(Date date, String pattern, int num) {
if (date == null)
date = new Date(System.currentTimeMillis());
if (pattern == null)
pattern = "yyyy-MM-dd HH:mm";
Calendar cal = null;
SimpleDateFormat fo = new SimpleDateFormat();
fo.applyPattern(pattern);
try {
fo.format(date);
cal = fo.getCalendar();
cal.add(Calendar.DATE, num);
} catch (Exception e) {
}
return fo.format(cal.getTime());
}

/**
* 算出两个时间的相差天数
* Created on 2014-6-6
* @param dateBegin
* @param dateEnd
* @return
*/
public static int subtrationDate(Date dateBegin, Date dateEnd) {

GregorianCalendar gc1 = new GregorianCalendar(dateBegin.getYear(),
dateBegin.getMonth(), dateBegin.getDate());
GregorianCalendar gc2 = new GregorianCalendar(dateEnd.getYear(),
dateEnd.getMonth(), dateEnd.getDate());
// the above two dates are one second apart
Date d1 = gc1.getTime();
Date d2 = gc2.getTime();
long l1 = d1.getTime();
long l2 = d2.getTime();
long difference = l2 - l1;
int date = (int) (difference / 24 / 60 / 60 / 1000);
return date;

}

// 当前日期前几天或者后几天的日期
public static Date afterNDay(int n) {
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, n);
Date d2 = c.getTime();
return d2;
}

// 当前日期前几天或者后几天的日期
public static Date afterNDays(Timestamp time, int n) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time.getTime());
c.add(Calendar.DATE, n);
Date d2 = c.getTime();
return d2;
}

public static Timestamp transDate(Date date) {
if (date != null) {
long time = date.getTime();
return new Timestamp(time);
}
return null;
}

public static Date transTimestamp(Timestamp time) {
if (time != null) {
long t = time.getTime();
return new Date(t);
}
return null;
}

// 时间段的第一个时间
public static java.sql.Timestamp stringToTime1(String d) {
java.sql.Timestamp t = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

Date d1;
try {
if (StringUtils.isNotEmpty(d)) {
d1 = df.parse(d);
t = new Timestamp(d1.getTime());
}
} catch (ParseException e) {
e.printStackTrace();
}
return t;
}

// 时间段的第二个时间
public static java.sql.Timestamp stringToTime2(String d) {
java.sql.Timestamp t = null;
//StringUtils
if (StringUtils.isNotEmpty(d)) {
t = Timestamp.valueOf(d + " 23:59:59");
}
return t;
}

public static Calendar getYesterDayBegin() {
Calendar before = Calendar.getInstance();

before
.set(Calendar.DAY_OF_MONTH,
before.get(Calendar.DAY_OF_MONTH) - 1);
before.set(Calendar.HOUR_OF_DAY, 0);
before.set(Calendar.MINUTE, 0);
before.set(Calendar.SECOND, 0);
before.set(Calendar.MILLISECOND, 0);

return before;
}

/**
* 查看昨天的日期 还需要调用transCalendarToTimestamp方法
* Created on 2014-6-6
* @return
*/
public static Calendar getYesterDayEnd() {
Calendar after = Calendar.getInstance();
after.set(Calendar.DAY_OF_MONTH, after.get(Calendar.DAY_OF_MONTH) - 1);
after.set(Calendar.HOUR_OF_DAY, 23);
after.set(Calendar.MINUTE, 59);
after.set(Calendar.SECOND, 59);
after.set(Calendar.MILLISECOND, 999);
return after;
}

/**
* Calendar和Timestamp转换
* @param cal
* @return
*/
public static Timestamp transCalendarToTimestamp(Calendar cal)
{
Timestamp ts = new Timestamp(cal.getTimeInMillis());
return ts;
}

/**
* 根据Timestamp类型参数 返回年后两位月日(例如:140606)
* Created on 2014-6-6
* @param time
* @return String
*/
public static String transTimestamptostr(Timestamp time) {
if (time != null) {

java.util.Calendar c = Calendar.getInstance();
c.setTime(time);
String year = String.valueOf(c.get(c.YEAR));
String month = String.valueOf(c.get(c.MONTH) + 1);
String day = String.valueOf(c.get(c.DATE));

if (month.length() < 2)
month = "0" + month;
if (day.length() < 2)
day = "0" + day;
return year.substring(2, 4) + month + day;

}
return null;
}

/**
* 根据Calendar日历返回String
* Created on 2014-6-6
* @param cal
* @return
*/
public static String getDataString(Calendar cal)
{
Calendar now=cal;
String time=now.get(Calendar.YEAR)+"-"+(now.get(Calendar.MONTH)+1)+"-"+now.get(Calendar.DAY_OF_MONTH)+" "+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+":"+now.get(Calendar.SECOND);
return time;
}


public static Calendar parseCalendarDate(String date) {
Calendar d11 = new GregorianCalendar();
Date d1 = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");// 时间格式自己设置
try { // 一定要放到try里面,不然会报错的
d1 = sdf.parse(date);
} catch (Exception e) {
}

d11.setTime(d1); // OK了,d11就是结果了
return d11;
}

public static Timestamp calendar2Timestamp(Calendar cal){
return new Timestamp(cal.getTimeInMillis());
}

public static String getDatePath(){
return DateHelper.CalendarToStrByMark(Calendar.getInstance(), "yyyyMMdd");
}
public static String getDatePath(Calendar cal,String pattern){
if(pattern==null){
pattern="yyyy-MM-dd hh:mm:ss";
}
SimpleDateFormat sf=new SimpleDateFormat(pattern);
return sf.format(cal.getTime());
}
public static String getDateTimePath(){
return DateHelper.CalendarToStrByMark(Calendar.getInstance(), "yyyyMMddHHmmss");
}

//Date转化为Calendar
public static Calendar date2Calendar(Date d){
Calendar cal=Calendar.getInstance();
cal.setTime(d);
return cal;
}

/**
* 日期比较是否相等
* @param d1
* @param d2
* @param type 比较方式,complete,date,
* @return boolean
* @author zhou jun
*/
public static boolean compere(Date d1, Date d2, String type)
{
if(type.equals("date")){
String pattern = "yyyy-MM-dd";
String date1 = formatDate(d1, pattern);
String date2 = formatDate(d2, pattern);
//System.out.println(date1+date2);
if(date1.equals(date2)){
return true;
}
return false;
}
else
{
return d1.equals(d2);
}
}

/**
* 功能: 将日期对象按照某种格式进行转换,返回转换后的字符串
*
* @param date 日期对象
* @param pattern 转换格式 例:yyyy-MM-dd
* @author yanhechao
*/
public static String DateToString(Date date, String pattern) {
String strDateTime = null;
SimpleDateFormat formater = new SimpleDateFormat(pattern);
strDateTime = date == null ? null : formater.format(date);
return strDateTime;
}




[size=large][b]字符串处理类:[/b][/size]



public class StringUtils {

public static String sqlnull(String source) {
if (source == null) {
return "";
} else {
return source;
}
}

private static StringUtils classInstance = new StringUtils();

public static final String EMPTY_STRING_ARRAY[] = new String[0];

public static StringUtils getInstance() {
return classInstance;
}

private StringUtils() {
}

public static String[] getStrAddress(String str) {
String[] strAddress = str.split("<br>");
return strAddress;

}

public static boolean isNumeric(String str) {
if (str == null)
return false;
int sz = str.length();
if (sz == 0)
return false;
for (int i = 0; i < sz; i++)
if (!Character.isDigit(str.charAt(i)))
return false;

return true;
}

public static String filterText(String content) {
content = content.replaceAll("\\[img\\]", "<img src=");

content = content.replaceAll("\\[\\/img\\]", " />");

content = content.replaceAll("\\[code\\]",
"<table width=100% border=1 bgcolor=#99FFFF><tr><td><p>");
content = content.replaceAll("\\[\\/code\\]", "</p></td></tr></table>");

return content;
}

// 验证字符是否日期
public static boolean isDate(String str, String format) {
Date dp1;
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);// 这个的功能是不把1996-13-3 转换�?1997-1-3
try {
dp1 = sdf.parse(str);

} catch (Exception e) {
return false;
}
return true;
}

public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}

public static boolean isNotEmpty(String str) {
return str != null && str.length() > 0;
}

public static String substring(String str, int start, int end) {
if (str.length() <= end)
end = str.length();
String temp = str.substring(start, end);
if (str.length() > temp.length())
temp += "...";
return temp;
}

public static int lastIndexOf(String str, char searchChar) {
if (str == null || str.length() == 0)
return -1;
else
return str.lastIndexOf(searchChar);
}

public static int lastIndexOf(String str, char searchChar, int startPos) {
if (str == null || str.length() == 0)
return -1;
else
return str.lastIndexOf(searchChar, startPos);
}

public static int lastIndexOf(String str, String searchStr) {
if (str == null || searchStr == null)
return -1;
else
return str.lastIndexOf(searchStr);
}

public static int lastIndexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null)
return -1;
else
return str.lastIndexOf(searchStr, startPos);
}

public static String substring(String str, int start) {
if (str == null)
return null;
if (start < 0)
start = str.length() + start;
if (start < 0)
start = 0;
if (start > str.length())
return "";
else
return str.substring(start);
}

public static String[] split(String str) {
return split(str, null, -1);
}

@SuppressWarnings("unchecked")
public static String[] split(String str, char separatorChar) {
if (str == null)
return null;
int len = str.length();
if (len == 0)
return EMPTY_STRING_ARRAY;
List list = new ArrayList();
int i = 0;
int start = 0;
boolean match = false;
while (i < len)
if (str.charAt(i) == separatorChar) {
if (match) {
list.add(str.substring(start, i));
match = false;
}
start = ++i;
} else {
match = true;
i++;
}
if (match)
list.add(str.substring(start, i));
return (String[]) list.toArray(new String[list.size()]);
}

public static String[] split(String str, String separatorChars) {
return split(str, separatorChars, -1);
}

@SuppressWarnings("unchecked")
public static String[] split(String str, String separatorChars, int max) {
if (str == null)
return null;
int len = str.length();
if (len == 0)
return EMPTY_STRING_ARRAY;
List list = new ArrayList();
int sizePlus1 = 1;
int i = 0;
int start = 0;
boolean match = false;
if (separatorChars == null)
while (i < len)
if (Character.isWhitespace(str.charAt(i))) {
if (match) {
if (sizePlus1++ == max)
i = len;
list.add(str.substring(start, i));
match = false;
}
start = ++i;
} else {
match = true;
i++;
}
else if (separatorChars.length() == 1) {
char sep = separatorChars.charAt(0);
while (i < len)
if (str.charAt(i) == sep) {
if (match) {
if (sizePlus1++ == max)
i = len;
list.add(str.substring(start, i));
match = false;
}
start = ++i;
} else {
match = true;
i++;
}
} else {
while (i < len)
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match) {
if (sizePlus1++ == max)
i = len;
list.add(str.substring(start, i));
match = false;
}
start = ++i;
} else {
match = true;
i++;
}
}
if (match)
list.add(str.substring(start, i));
return (String[]) list.toArray(new String[list.size()]);
}

public static boolean arrayContains(String[] arr, String str) {
if (str == null)
return false;
for (String s : arr) {
if (s.equalsIgnoreCase(str))
return true;
}
return false;
}

public static void sort(int[] data) {
for (int i = 0; i < data.length; i++) {
for (int j = data.length - 1; j > i; j--) {
if (data[j] < data[j - 1]) {
swap(data, j, j - 1);
}
}
}
}

public static void sortList(List data) {
for (int i = 0; i < data.size(); i++) {
for (int j = data.size() - 1; j > i; j--) {
@SuppressWarnings("unused")
String sdfsd = ((Object[]) data.get(j))[1] + "";
if (Double.parseDouble(((Object[]) data.get(j))[1] + "") < Double
.parseDouble(((Object[]) data.get(j - 1))[1] + "")) {
swapList(data, j, j - 1);
}
sdfsd = null;
}
}
}

public static void sortDescList(List data) {
for (int i = 0; i < data.size(); i++) {
for (int j = data.size() - 1; j > i; j--) {
@SuppressWarnings("unused")
String sdfsd = ((Object[]) data.get(j))[1] + "";
if (Double.parseDouble(((Object[]) data.get(j))[1] + "") > Double
.parseDouble(((Object[]) data.get(j - 1))[1] + "")) {
swapList(data, j, j - 1);

}
sdfsd = null;
}
}

}

@SuppressWarnings("unchecked")
private static void swapList(List data, int i, int j) {
Object temp = data.get(i);
data.set(i, data.get(j));
data.set(j, temp);
temp = null;
}

private static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}

public static String formatIntToStr(int num, String pattern) {
DecimalFormat df = new DecimalFormat(pattern);

return df.format(num);
}

public static Long[] string2Long(String[] strs) {
if (strs == null) {
return new Long[0];
}

Long[] ls = new Long[strs.length];

for (int i = 0; i < strs.length; i++) {
ls[i] = Long.valueOf(strs[i]);
}

return ls;
}

public static String toChi(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");

return isValidUtf8(bytes, bytes.length) ? new String(bytes, "utf-8")
: new String(bytes);
} catch (Exception ex) {
}

return null;
}

public static boolean isValidUtf8(byte[] b, int aMaxCount) {
int lLen = b.length;
int lCharCount = 0;

for (int i = 0; (i < lLen) && (lCharCount < aMaxCount); ++lCharCount) {
byte lByte = b[i++]; // to fast operation, ++ now, ready for the
// following for(;;)

if (lByte >= 0) {
continue; // >=0 is normal ascii
}

if ((lByte < (byte) 0xc0) || (lByte > (byte) 0xfd)) {
return false;
}

int lCount = (lByte > (byte) 0xfc) ? 5 : ((lByte > (byte) 0xf8) ? 4
: ((lByte > (byte) 0xf0) ? 3 : ((lByte > (byte) 0xe0) ? 2
: 1)));

if ((i + lCount) > lLen) {
return false;
}

for (int j = 0; j < lCount; ++j, ++i)
if (b[i] >= (byte) 0xc0) {
return false;
}
}

return true;
}

public static Date afterDate(String date, String pattern) {
SimpleDateFormat fo = new SimpleDateFormat();

if (pattern == null) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
fo.applyPattern(pattern);
Date tempdate = null;
try {
tempdate = fo.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tempdate;
}

public static boolean between(Date startDate, Date endDate) {
if (startDate.after(endDate))
return false;

return true;
}

public static Integer getStateNow() {
Date d = new Date();
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
Integer i = Integer.parseInt(s.format(d));
return i;
}

public static void main(String[] args) {
System.out.println(getStateBeforeNow());
System.out.println(isDate("2009-07-27", "yyyy-MM-dd"));
System.out.println(getStateNow());
}

public static Integer getStateBeforeNow() {
Date d = new Date();

int day = d.getDate();
if (day == 1) {
d.setDate(31);
} else {
d.setDate(d.getDate() - 1);
}
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
Integer i = Integer.parseInt(s.format(d));
return i;
}

public static String convertToBr(String content) {
if (StringUtils.isNotEmpty(content)) {
content = content.replaceAll("\r\n", "<br />");
}

return content;
}


public static String fillString(String originalStr, String fillChar,
int fillStrLen) {
if (isEmpty(originalStr)) {
originalStr = "";
}
if (originalStr.length() > fillStrLen) {
return originalStr;
}
StringBuffer fillStr = new StringBuffer();
for (int i = 0; i < fillStrLen - originalStr.length(); i++) {
fillStr.append(fillChar);
}
return fillStr.toString() + originalStr;
}


public static boolean checkBigDecimal(String targetString) {
BigDecimal tmp = null;
try {
tmp = new BigDecimal(targetString);
} catch (NumberFormatException e) {
}
if (tmp != null) {
return true;
}
return false;
}

public static Object sqlnullLimit(String source, int limit) {
String result = "";

if (source == null) {
result = "";
} else {
result = source;
}

if (result.length() > limit) {
result = result.substring(0, limit);
}

return result;
}



public static boolean checkEmail(String mail) {
String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(mail);
return m.find();
}


public static void getRandomString(StringBuffer str,int length) {
for (int i = 0; i < length; i++) {
int n = new Double(Math.random() * 26 + 65).intValue();
str.append((char) n);
}
}


public static void getRandomNumString(StringBuffer str,int length) {
for (int i = 0; i < length; i++) {
int n = new Double(Math.random() * 10).intValue();
str.append(n);
}
}

private void createRandomAllString(StringBuffer str,int length){
String[] code = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K"
,"L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
Random rd = new Random(System.currentTimeMillis());
for (int i=1;i<=length;i++){
str.append((code[rd.nextInt(36)]));
}
}

public static String addTowStr(String str1, String str2)
{
if(isNumeric(str1) && isNumeric(str2))
{
return new BigDecimal(str1).add(new BigDecimal(str2)).toString();
}
return null;
}
/**
*
* <p>Discription:[时间戳转字符 ]</p>
* @param timestamp 需要转换的时间戳
* @param formatStr 需要转换的格式[yyyy-MM-dd]
* @return string
*/
public static String TimestampToString(Timestamp timestamp,String formatStr)
{
String strTimestamp=null;
SimpleDateFormat df=new SimpleDateFormat(formatStr);
try {
strTimestamp = df.format(timestamp);
} catch (Exception e) {
e.printStackTrace();
}

return strTimestamp;
}

}



自己看的调用吧,希望能帮到一些刚入门的童鞋
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值