首页 > 代码库 > 时间与字串的转换,date/string

时间与字串的转换,date/string

package com.neweb.botCashier.util;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

import com.neweb.botCashier.base.exception.AppException;

public class DateUtils {

private static Logger logger = Logger.getLogger(DateUtils.class);

public static final String DATE_PATTERN_DEFAULT = "yyyyMMdd";
public static final String TIME_PATTERN_DEFAULT = "HHmmss";

/**
* 字串轉時間
* @param str 時間字串
* @param fmt 字串格式
* @return Date
*/
public static Date stringToDate(String str, String fmt){
if (null == str || "".equals (str))
return null;

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(fmt);
try{
return sdf.parse(str);
}catch (java.text.ParseException pe){
logger.error(pe);
}
return null;
}

/**
* 字串轉日期,預設格式yyyyMMdd
* @param str 日期字串
* @return Date
*/
public static Date stringToDate(String str){
if (null == str || "".equals (str))
return null;
return stringToDate (str, DATE_PATTERN_DEFAULT);
}

/**
* 日期轉字串
* @param date 日期
* @param fmt 字串格式
* @return String
*/
public static String dateToString(Date date, String fmt){
if (null == date)
return "";

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(fmt);
try{
return new String(sdf.format(date, new StringBuffer(), new java.text.FieldPosition(0)));
}catch (NullPointerException ne){
logger.error(ne);
}
return null;
}

/**
* 日期轉字串,預設格式yyyyMMdd
* @param date 日期
* @return String
*/
public static String dateToString(Date date){
if (null == date)
return "";
return dateToString(date, DATE_PATTERN_DEFAULT);
}

/**
* 日期轉數字
* @param date
* @return
*/
public static int dateToInt(Date date){
try{
return Integer.parseInt(DateUtils.dateToString(date));
}catch (Exception e){
logger.error(e.getMessage(), e);
return 0;
}
}

/**
* 數字日期時間轉日期時間
* @param date
* @param time
* @return
*/
public static Date intToDate(int date, int time){
String fullDateTime = intDateToStr(date) + intTimeToStr(time);
return stringToDate(fullDateTime, "yyyyMMddHHmmss");
}

/**
* 時間轉字串,預設格式HHmmss
* @param date 時間
* @return String
*/
public static String timeToString(Date date){
if (null == date)
return "";
return dateToString(date, TIME_PATTERN_DEFAULT);
}
/**
* 時間轉字串,預設格式HHmmss
* @param date 時間
* @return String
*/
public static String timeToString(Date date, String fmt){
if (null == date)
return "";
return dateToString(date, fmt);
}
/**
* 時間轉數字
* @param date
* @return
*/
public static int timeToInt(Date date){
try{
return Integer.parseInt(DateUtils.timeToString(date));
}catch (Exception e){
logger.error(e.getMessage(), e);
return 0;
}
}

/**
* 數字日期轉字串
* @param date
* @param fmt
* @return
*/
public static String intDateToStr(int date, String fmt){
return dateToString(stringToDate(String.format("%08d", date)), fmt);
}

/**
* 數字日期轉字串, 預設格式yyyyMMdd
* @param date
* @return
*/
public static String intDateToStr(int date){
return intDateToStr(date, DATE_PATTERN_DEFAULT);
}

/**
* 數字時間轉字串
* @param time
* @param fmt
* @return
*/
public static String intTimeToStr(int time, String fmt){
return dateToString(stringToDate(String.format("%06d", time), TIME_PATTERN_DEFAULT), fmt);
}

/**
* 數字時間轉字串, 預設格式HHmmss
* @param time
* @return
*/
public static String intTimeToStr(int time){
return intTimeToStr(time, TIME_PATTERN_DEFAULT);
}


/**
* 取得系統時間
* @return Date
*/
public static Date getSysDate() {
return Calendar.getInstance().getTime();
}

/**
* 取得昨日
* @return
*/
public static Date getYesterday(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}

/**
* 取得明日(隔日)
* @return
*/
public static Date getTomorrow(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, +1);
return cal.getTime();
}

/**
* 增加日期月份
* @param dt 時間
* @param amount 增加月份
* @return Date
*/
public static Date addMonth(Date dt, int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.MONTH, amount);
return cal.getTime();
}

/**
* 增加日期天數
* @param dt 時間
* @param amount 增加天數
* @return Date
*/
public static Date addDate(Date dt, int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.DAY_OF_MONTH, amount);
return cal.getTime();
}

/**
* 增加分鐘數
* @param dt 時間
* @param amount 增加分鐘數
* @return
*/
public static Date addMinute(Date dt, int amount){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.MINUTE, amount);
return cal.getTime();
}

/**
* 計算時間差距
* @param sDate 起始時間
* @param eDate 結束時間
* @return
*/
public static long totalSec(Date sDate, Date eDate){
long sTime = sDate.getTime();
long eTime = eDate.getTime();
long total = eTime - sTime;
return total;
}

/**
* 檢查信用卡有效月年
* [v1 > v2, 回傳大於0],
* [v1 = v2, 回傳0],
* [v1 < v2, 回傳小於0]
* @param v1
* @param v2
* @return
*/
public static int compareVaildYearMonth(String v1, String v2){
String v1YM = v1.substring(2) + v1.substring(0, 2);
String v2YM = v2.substring(2) + v2.substring(0, 2);
return v1YM.compareTo(v2YM);
}

/**
* 轉換信用卡過期日,MMyy轉成yyyyMM
* @param MMyy
* @return yyyMM
*/
public static String convertCardtValidYearMonth(String MMyy){
try {
//須為數字
Integer.parseInt(MMyy);
//更換年月
String sysYear = DateUtils.dateToString(getSysDate(), "yyyy");
String result = sysYear.substring(0, 2)
+ MMyy.substring(2)
+ MMyy.substring(0, 2);
return result;
}catch(Exception e){
logger.info(e.getMessage(), e);
return null;
}

}

/**
* 西元年字串轉民國年字串
* @param dateStr
* @return
*/
public static String dateStrToROC(String dateStr){
try{
Date date = DateUtils.stringToDate(dateStr);
int dateInt = DateUtils.dateToInt(date);
return String.valueOf(dateInt - 19110000);
}catch(Exception e){
logger.info(e.getMessage(), e);
return null;
}

}

/**
* 民國年字串轉西元年字串
* @param dateStr
* @return
*/
public static String ROCToDateStr(String rocStr){
try{
int dateInt = Integer.parseInt(rocStr) + 19110000;
return String.valueOf(dateInt);
}catch(Exception e){
logger.info(e.getMessage(), e);
return null;
}

}

/**
* 計算剩餘時間
* @param limitDate 截止時間
* @param currentDate 當下時間
* @return long[]回傳 [index:0] 分, [index:1] 秒
*/
public static long[] getVerifyRemainTime(Date limitDate, Date currentDate){
long[] result = new long[]{0l, 0l};
long totalMSec = limitDate.getTime() - currentDate.getTime();
long totalSec = (new BigDecimal(totalMSec).divide(new BigDecimal(1000), 0, BigDecimal.ROUND_HALF_UP)).longValue();
System.out.println(totalSec);
result[0] = totalSec / 60l;
result[1] = totalSec % 60l;
return result;
}

/**
* 獲得日曆日:該年的第×天
* @param currentDate
* @return
*/
public static int getCalandaDay(Date currentDate){
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
return cal.get(Calendar.DAY_OF_YEAR);
}

/**
* 取得系統西元年字串日期 EX:20120101
*
* @param sign
* @return
*/
public static String getSystemDate() {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy" + "MM" + "dd"); // + "HH" + "mm" + "ss"
return format.format(date);
}
/**
* 取得系統西元年字串時間 EX:171020
*
* @param sign
* @return
*/
public static String getSystemTime() {
Calendar cal=Calendar.getInstance();
String hours= "0" + String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
String minute= "0" + String.valueOf(cal.get(Calendar.MINUTE));
String second= "0" + String.valueOf(cal.get(Calendar.SECOND));
String systime = hours.substring(hours.length() - 2) + minute.substring(minute.length() - 2 ) + second.substring(second.length() - 2 );
return systime;
}
public static void main(String[] args) {
try{
Date sendDate = DateUtils.intToDate(20121101, 172440);
Date afert5MDate = DateUtils.addMinute(sendDate, 5);
System.out.println(afert5MDate);
Date sysDate = DateUtils.getSysDate();
System.out.println(sysDate);
if (sysDate.before(afert5MDate)){
long[] times = DateUtils.getVerifyRemainTime(afert5MDate, sysDate);
throw AppException.getValidateErr("IDX1023", new String[]{String.valueOf(times[0]), String.valueOf(times[1])});
}
}catch(Exception e){
System.out.println(e.getMessage());
}

}
}

时间与字串的转换,date/string