📄 dateutil.java
字号:
package com.common.utils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import com.common.Constants;
/**
* Date Utility Class
* This is used to convert Strings to Dates and Timestamps
*/
public class DateUtil {
//~ Static fields/initializers =============================================
private static Log log = LogFactory.getLog(DateUtil.class);
private static String defaultDatePattern = null;
private static String timePattern = "HH:mm";
//~ Methods ================================================================
/**
* Return default datePattern (yyyy-MM-dd)
* @return a string representing the date pattern on the UI
*/
public static synchronized String getDatePattern() {
Locale locale = LocaleContextHolder.getLocale();
try {
defaultDatePattern = ResourceBundle.getBundle(Constants.BUNDLE_KEY, locale)
.getString("date.format");
} catch (MissingResourceException mse) {
defaultDatePattern = "yyyy-MM-dd";
}
return defaultDatePattern;
}
/**
* This method attempts to convert an Oracle-formatted date
* in the form dd-MMM-yyyy to mm/dd/yyyy.
*
* @param aDate date from database as a string
* @return formatted string for the ui
*/
public static final Date getFormateDate(Date aDate) {
String DatePattern="yyyy-MM-dd";
SimpleDateFormat df = null;
String returnValue = "";
if (aDate != null) {
df = new SimpleDateFormat(DatePattern);
returnValue = df.format(aDate);
}
return convertStringToDate(DatePattern,returnValue);
}
/**
* This method attempts to convert an Oracle-formatted date
* in the form dd-MMM-yyyy to mm/dd/yyyy.
*
* @param aDate date from database as a string
* @return formatted string for the ui
*/
public static final String getDate(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";
if (aDate != null) {
df = new SimpleDateFormat(getDatePattern());
returnValue = df.format(aDate);
}
return (returnValue);
}
/**
* This method generates a string representation of a date/time
* in the format you specify on input
*
* @param aMask the date pattern the string is in
* @param strDate a string representation of a date
* @return a converted Date object
* @see java.text.SimpleDateFormat
* @throws ParseException
*/
public static final Date convertStringToDate(String aMask, String strDate)
{
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(aMask);
if (log.isDebugEnabled()) {
log.debug("converting '" + strDate + "' to date with mask '"
+ aMask + "'");
}
try {
date = df.parse(strDate);
} catch (ParseException pe) {
//log.error("ParseException: " + pe);
}
return (date);
}
/**
* This method returns the current date time in the format:
* MM/dd/yyyy HH:MM a
*
* @param theTime the current time
* @return the current date/time
*/
public static String getTimeNow(Date theTime) {
return getDateTime(timePattern, theTime);
}
/**
* get thi week day of the time
* @param strDate
* @return
*/
public static int getWeekDay(String strDate)
{
Calendar cal=new GregorianCalendar();
cal.setTime(convertStringToDate(strDate));
return cal.getTime().getDay();
}
/**
* This method returns the current date in the format: MM/dd/yyyy
*
* @return the current date
* @throws ParseException
*/
public static Calendar getToday() throws ParseException {
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
// This seems like quite a hack (date -> string -> date),
// but it works ;-)
String todayAsString = df.format(today);
Calendar cal = new GregorianCalendar();
cal.setTime(convertStringToDate(todayAsString));
return cal;
}
/**
* This method generates a string representation of a date's date/time
* in the format you specify on input
*
* @param aMask the date pattern the string is in
* @param aDate a date object
* @return a formatted string representation of the date
*
* @see java.text.SimpleDateFormat
*/
public static final String getDateTime(String aMask, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";
if (aDate == null) {
log.error("aDate is null!");
} else {
df = new SimpleDateFormat(aMask);
returnValue = df.format(aDate);
}
return (returnValue);
}
/**
* This method generates a string representation of a date based
* on the System Property 'dateFormat'
* in the format you specify on input
*
* @param aDate A date to convert
* @return a string representation of the date
*/
public static final String convertDateToString(Date aDate) {
return getDateTime(getDatePattern(), aDate);
}
/**
* This method converts a String to a date using the datePattern
*
* @param strDate the date to convert (in format MM/dd/yyyy)
* @return a date object
*
* @throws ParseException
*/
public static Date convertStringToDate(String strDate)
{
Date aDate = null;
try {
if (log.isDebugEnabled()) {
log.debug("converting date with pattern: " + getDatePattern());
}
aDate = convertStringToDate(getDatePattern(), strDate);
} catch (Exception pe) {
log.error("Could not convert '" + strDate
+ "' to a date, throwing exception");
pe.printStackTrace();
/* throw new ParseException(pe.getMessage(),
pe.getErrorOffset());*/
}
return aDate;
}
public static Timestamp getNowTimestamp(){
Date date=new Date();
return new java.sql.Timestamp(date.getTime());
}
public static java.sql.Date getNowSqlDate(){
Date date=new Date();
return new java.sql.Date(date.getTime());
}
public static java.sql.Date getNowSqlDate(Date date){
if(date!=null)
return new java.sql.Date(date.getTime());
else
return getNowSqlDate();
}
/**
* Default lenient setting for getDate.
*/
private static boolean LENIENT_DATE = false;
/**
* A "default" date format.
*/
// public static String ESCAPE_DATE_PATTERN = "yyyy-mm-dd";
/**
* Convert String to Date using given format.
* Returns null if conversion fails.
* Set lenient=false to disallow dates like 2001-9-32.
* http://java.sun.com/j2se/1.4/docs/api/java/text/SimpleDateFormat.html
* @author Hal Deadman
*/
public static Date getDate(String dateDisplay,
String format, boolean lenient) {
if (dateDisplay == null) {
return null;
}
DateFormat df = null;
try {
if (format==null) {
df = new SimpleDateFormat();
}
else {
df = new SimpleDateFormat(format);
}
// setLenient avoids allowing dates like 9/32/2001
// which would otherwise parse to 10/2/2001
df.setLenient(false);
return df.parse(dateDisplay);
}
catch(ParseException e) {
return null;
}
}
/**
* Convert String to Date using given format.
* Returns null if conversion fails.
* Uses "strict" coNversion (lenient=false).
* @author Hal Deadman
*/
public static Date getDate(String dateDisplay, String format) {
return getDate(dateDisplay,format,LENIENT_DATE);
}
/**
* Convert String to Date using a medium (weekday day month year) format.
* Returns null if conversion fails.
* Uses "strict" coNversion (lenient=false).
* @author Hal Deadman
*/
public static Date getDate(String dateDisplay) {
return getDate(dateDisplay,null,LENIENT_DATE);
}
// 当前日期加减n个月后的日期,返回java.sql.Date
public static java.sql.Date nMonthsAfterOneDate(java.sql.Date basicDate,int n) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(basicDate);
rightNow.add(Calendar.MONTH,+n);
return java.sql.Date.valueOf(df.format(rightNow.getTime()));
//return rightNow.gett
}
// 当前日期加减n个月后的日期,返回String
public static String nMonthsAfterOneDateString(Date basicDate,int n) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(basicDate);
rightNow.add(Calendar.MONTH,+n);
return df.format(rightNow.getTime());
}
public static String getNowTimeNum() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return sdf.format(Calendar.getInstance().getTime());
}
public static String getYearMonthNum(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
return sdf.format(Calendar.getInstance().getTime());
}
public static String getDate(Date date,String formatPattern){
try {
SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
return sdf.format(date);
}catch(Exception e) {
return null;
}
}
/**
* 给定一个日期型字符串,返回加减n天后的日期型字符串
*/
public static String nDaysAfterOneDateString(String basicDate,int n) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date tmpDate = null;
try {
tmpDate = df.parse(basicDate);
}
catch(Exception e){
return null;
}
long nDay=(tmpDate.getTime()/(24*60*60*1000)+1+n)*(24*60*60*1000);
tmpDate.setTime(nDay);
return df.format(tmpDate);
}
/**
* 判断字符是不是时间格式
* @param dateTime
* @return
*/
public static boolean isDate(String dateTime)
{
StringBuffer regex=new StringBuffer();
regex.append("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])");
regex.append("|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?" );
regex.append("((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))" );
regex.append("[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))" );
regex.append("|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|" );
regex.append("(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))" );
regex.append("\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
Pattern p = Pattern.compile(regex.toString());
Matcher matcher=p.matcher(dateTime);
return matcher.matches();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -