- 浏览: 589084 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
Garlic_90:
ireport分页的话代码写起来有些复杂,我以前试过,比较简单 ...
ireport分页显示 -
feijiing:
nice,problem solved,thanks!
虚拟机安装centos no valid devices were found on which to cereate new file systems -
Jocken:
引用的jar包需要怎么加在命令里面?十多个呢,为什么配在MAN ...
linux 如何运行jar包 -
xiaoqiao800:
看到你的问题,有帮助,我之前都是手动的clear项目下的cla ...
The project cannot be built until build path errors are resolved -
mfkdzhou:
楼主好,我现在也遇到这个问题,可以把源代码发一份不?谢谢了。8 ...
java打印
1.如何计算某日期所在周的起止日期:
public static void main(String args[])
{
Calendar cal = Calendar.getInstance();
System.out.println("今天的日期: " + cal.getTime());
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
System.out.println("本周第一天: " + cal.getTime());
cal.add(Calendar.DATE, 6);
System.out.println("本周末: " + cal.getTime());
}
2.如何计算当前时间之前的某个时间点
Calendar cal = Calendar.getInstance();
//当前时期往前推两天
cal.add(Calendar.DATE,-2);
//当前时间往前推两个小时
cal.add(Calendar.HOUR,-2);
//当前时间往前推两个月
cal.add(Calendar.MONTH,-2);
3.一些常用的日期处理
/**
* This DateUtil class provides methods for formatting, validating and
* retrieving different types of dates. <BR><BR> Note: Struts validator also
* provides a similar Date validator, one may use either one of one's
* preference for validating the validility of the date.
*
* @author Framework Team
* @version 1.0
* @class DateUtil
* @since 12/12/2002
*/
public class DateUtil {
/**
* A log instance for this class
*/
protected static Logger log = Logger.getLogger(DateUtil.class.toString());
// Dates constants
/**
* "JAN" to represent January
*/
public static final String MTH_JAN = "Jan";
/**
* "FEB" to represent February
*/
public static final String MTH_FEB = "Feb";
/**
* "MAR" to represent March
*/
public static final String MTH_MAR = "Mar";
/**
* "APR" to represent April
*/
public static final String MTH_APR = "Apr";
/**
* "MAY" to represent May
*/
public static final String MTH_MAY = "May";
/**
* "JUNE" to represent June
*/
public static final String MTH_JUN = "Jun";
/**
* "JUL" to represent July
*/
public static final String MTH_JUL = "Jul";
/**
* "AUG" to represent August
*/
public static final String MTH_AUG = "Aug";
/**
* "SEP" to represent September
*/
public static final String MTH_SEP = "Sep";
/**
* "OCT" to represent October
*/
public static final String MTH_OCT = "Oct";
/**
* "NOV" to represent November
*/
public static final String MTH_NOV = "Nov";
/**
* "DEC" to represent December
*/
public static final String MTH_DEC = "Dec";
/**
* The date pattern in this format 'ddMMyyyy HHmm'
*/
public static String DATETIME_FORMAT = "ddMMyyyy HHmm";
//Add By Xi Wei on 21 Dec 2004
public static String DATE_FORMAT = "dd MMM yyyy";
public static String TIMESTAMP_FORMAT = "dd MMM yyyy HH:mm:ss";
/**
* Returns a date object from input string indicating year, month and day
*
* @param year Year Indicator
* @param month Month indicator, 1=jan 2=feb ...
* @param day Date indicator eg: any day from 1...31.
* @return date java.util.Date object in millisecond.
* @since 15/05/2000
*/
public static Date getDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, day, 0, 0, 0);
return cal.getTime();
}
/**
* Compares the 2 dates: Returns true if the 2 dates are equal.
*
* @param date1 Date to compare
* @param date2 Date to compare
* @return true if <code>date1</code> equals to <code>date2</code>.
* @since 24/04/2001
*/
public static boolean isDateEqual(Date date1, Date date2) {
if ((date1 == null) || (date2 == null)) {
return false;
}
return resetTime(date1).compareTo(resetTime(date2)) == 0;
}
/**
* Sets the default timezone to the specified timezone ID. Note: The
* system time will remain unchanged. Only the Time zone for the current
* thread is set.
*
* @param timeZoneID The timezone ID. Example: "America/Los_Angeles", "CCT"
* which stands for China/Taiwan = S'pore
*/
public static void setDefaultTimeZone(String timeZoneID) {
TimeZone.setDefault(TimeZone.getTimeZone(timeZoneID));
}
/**
* Calculates the elapsed time between 2 dates. The elapsed time calculated
* could either be in years, months or days
*
* @param type (int) The variable type determines the calculation of the
* elapsed time to be based on either years, months or days. To
* compute the elapsed time in year input type set to Calendar.YEAR
* To compute the elapsed time in month input type set to
* Calendar.MONTH By default the elapsed time will compute in days
* @param startDate start date
* @param endDate end date
* @return the elapsed time (int)
*/
public static final int getElapsedTime(int type, Date startDate,
Date endDate) {
int elapsed = 0;
if ((startDate == null) || (endDate == null)) {
return -1;
}
if (startDate.after(endDate)) {
return -1;
}
GregorianCalendar gc1 = (GregorianCalendar) Calendar.getInstance();
GregorianCalendar gc2 = (GregorianCalendar) gc1.clone();
gc1.setTime(startDate);
gc2.setTime(endDate);
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
if ((type != Calendar.MONTH) && (type != Calendar.YEAR)) {
type = Calendar.DATE;
}
if (type == Calendar.MONTH) {
gc1.clear(Calendar.DATE);
gc2.clear(Calendar.DATE);
}
if (type == Calendar.YEAR) {
gc1.clear(Calendar.DATE);
gc2.clear(Calendar.DATE);
gc1.clear(Calendar.MONTH);
gc2.clear(Calendar.MONTH);
}
while (gc1.before(gc2)) {
gc1.add(type, 1);
elapsed++;
}
return elapsed;
}
/**
* This method will determine if the date is the last day of the month
*
* @param date date
* @return returns true if the date falls on the last day of the month else
* returns false
*/
public static final boolean isEndOfTheMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (cal.get(Calendar.DATE) == maxDay) {
return true;
}
return false;
}
/**
* This method will determine if the date is the last day of the year
*
* @param date date
* @return returns true if the date falls on the last day of the year else
* returns false
*/
public static final boolean isEndOfTheYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if ((cal.get(Calendar.MONTH) == 11) && (cal.get(Calendar.DATE) == 31)) {
return true;
}
return false;
}
/**
* This method will return the last day of the months
*
* @param date date
* @return returns the last day of the month
*/
public static final int getLastDayOfTheMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* Returns the numeric value of the specified month
*
* @param month The 3 letter month representation. Example: "Jan", "Feb", etc
* @return the numeric value of the specified month
*/
public static int getMthInInt(String month) {
if (month.equalsIgnoreCase(MTH_JAN)) {
return 1;
} else if (month.equalsIgnoreCase(MTH_FEB)) {
return 2;
} else if (month.equalsIgnoreCase(MTH_MAR)) {
return 3;
} else if (month.equalsIgnoreCase(MTH_APR)) {
return 4;
} else if (month.equalsIgnoreCase(MTH_MAY)) {
return 5;
} else if (month.equalsIgnoreCase(MTH_JUN)) {
return 6;
} else if (month.equalsIgnoreCase(MTH_JUL)) {
return 7;
} else if (month.equalsIgnoreCase(MTH_AUG)) {
return 8;
} else if (month.equalsIgnoreCase(MTH_SEP)) {
return 9;
} else if (month.equalsIgnoreCase(MTH_OCT)) {
return 10;
} else if (month.equalsIgnoreCase(MTH_NOV)) {
return 11;
} else if (month.equalsIgnoreCase(MTH_DEC)) {
return 12;
} else {
return 0;
}
}
/**
* Return the date of the next working day
*
* @return the date of the next working day
*/
public static Date getNextWorkingDay() {
Date nextWorkingDay = DateUtil.addDaysToDate(DateUtil.getSystemDate(), 1);
Calendar c = Calendar.getInstance();
c.setTime(nextWorkingDay);
int day = c.get(Calendar.DAY_OF_WEEK);
if (day == Calendar.SUNDAY) {
nextWorkingDay = DateUtil.addDaysToDate(nextWorkingDay, 1);
}
return nextWorkingDay;
}
/**
* Compares the 2 dates: Returns true if the start date is before the end
* date.
*
* @param startDate Starting date of a particular time period.
* @param endDate Ending date of a particular time period.
* @return true if the <code>startDate</code> is before
* <code>endDate</code>.
* @since 24/03/2001
*/
public static boolean isStartBeforeEndDate(Date startDate, Date endDate) {
if ((startDate == null) || (endDate == null)) {
return false;
}
return resetTime(startDate).compareTo(resetTime(endDate)) < 0;
}
/**
* This method will determine if the date occurs on the beginning of the
* month
*
* @param date date
* @return returns true if date is on the beginning of the month else
* returns false
*/
public static final boolean isStartOfTheMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (cal.get(Calendar.DATE) == 1) {
return true;
}
return false;
}
/**
* This method will return
* month
*
* @param date date
* @return returns month in int
*/
public static final int getMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.MONTH);
}
public static final int getYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.YEAR);
}
/**
* This method will determine if the date occurs at the beginning of the
* year
*
* @param date date
* @return returns true if the date occurs on the beginning of the year
* else returns false
*/
public static final boolean isStartOfTheYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if ((cal.get(Calendar.MONTH) == 1) && (cal.get(Calendar.DATE) == 1)) {
return true;
}
return false;
}
/**
* Returns the corresponding 3 letter string value of the month specified by numeric month value
*
* @param month The numeric value of the specified month
* @return the corresponding 3 letter string value of the month specified by numeric month value
*/
public static String getStrMth(int month) {
if (month == 1) {
return MTH_JAN;
} else if (month == 2) {
return MTH_FEB;
} else if (month == 3) {
return MTH_MAR;
} else if (month == 4) {
return MTH_APR;
} else if (month == 5) {
return MTH_MAY;
} else if (month == 6) {
return MTH_JUN;
} else if (month == 7) {
return MTH_JUL;
} else if (month == {
return MTH_AUG;
} else if (month == 9) {
return MTH_SEP;
} else if (month == 10) {
return MTH_OCT;
} else if (month == 11) {
return MTH_NOV;
} else if (month == 12) {
return MTH_DEC;
} else {
return "";
}
}
/**
* Calculates the duration in years, months and days.
*
* @param startDate Start Date of a period.
* @param endDate End date of a period.
* @return int [] result [0]=duration in years, [1]=duration in months,
* [2]=duration in days.
*/
public static final int[] computeDuration(Date startDate, Date endDate) {
Calendar from = Calendar.getInstance();
Calendar to = Calendar.getInstance();
from.setTime(startDate);
to.setTime(endDate);
int birthYYYY = from.get(Calendar.YEAR);
int birthMM = from.get(Calendar.MONTH);
int birthDD = from.get(Calendar.DAY_OF_MONTH);
int asofYYYY = to.get(Calendar.YEAR);
int asofMM = to.get(Calendar.MONTH);
int asofDD = to.get(Calendar.DAY_OF_MONTH);
int ageInYears = asofYYYY - birthYYYY;
int ageInMonths = asofMM - birthMM;
int ageInDays = asofDD - birthDD + 1;
if (ageInDays < 0) {
/*
* Guaranteed after this single treatment, ageInDays will be >= 0.
* that is ageInDays = asofDD - birthDD + daysInBirthMM.
*/
ageInDays += from.getActualMaximum(Calendar.DAY_OF_MONTH);
ageInMonths--;
}
if (ageInDays == to.getActualMaximum(Calendar.DAY_OF_MONTH)) {
ageInDays = 0;
ageInMonths++;
}
if (ageInMonths < 0) {
ageInMonths += 12;
ageInYears--;
}
if ((birthYYYY < 0) && (asofYYYY > 0)) {
ageInYears--;
}
if (ageInYears < 0) {
ageInYears = 0;
ageInMonths = 0;
ageInDays = 0;
}
int[] result = new int[3];
result[0] = ageInYears;
result[1] = ageInMonths;
result[2] = ageInDays;
return result;
}
/**
* Returns the current SQL date.
*
* @return Date
*/
public static java.sql.Date getSystemDate() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sysDate = new java.sql.Date(cal.getTime().getTime());
return sysDate;
}
/**
* Returns the current timestamp.
*
* @return Timestamp
*/
public static Timestamp getSystemTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
/**
* Returns true if the length of the year is of 4 digits
*
* @param s String value Year
* @return True if the year length is of 4 digits, False otherwise
* @since 20/04/2001
*/
public static boolean isValidYearFormat(String s) {
if (s == null) {
return false;
} else if (s.trim().length() == 4) {
return true;
}
return false;
}
/**
* This method convert the date to string
*
* @param date date
* @param strFormat the string format
* @return date as string format
*/
public static String getDate(Date date, String strFormat) {
return DateUtil.parseDate(date, strFormat);
}
/**
* Returns true if the String is a valid date.
*
* @param strDate The date in format ddmmyyyy.
* @return True, if it is a valid date. False, otherwise.
*/
public static boolean isValidDate(String strDate) {
return DateUtil.toDate(strDate, "ddMMyyyy") != null;
}
/**
* Returns true if the String is a valid date by specifying the date format to be verified.
*
* @param strDate The date.
* @param dateStrFormat The date format of the specified strDate
* @return True, if it is a valid date. False, otherwise.
*/
public static boolean isValidDate(String strDate, String dateStrFormat) {
return DateUtil.toDate(strDate, dateStrFormat) != null;
}
/**
* Add year, month or day to a date
* To subtract the specified number of Days to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 days from the specified date.
* The same applies to month and year.
*
* @param type (int). Indicates the input num value is in year, month, or
* days. Valid values are Calendar.YEAR, Calendar.MONTH,
* Calendar.DATE
* @param date (java.sql.Date).
* @param num (int). The value to be added to the input date.
* @return java.sql.Date.
*/
public static final Date addDate(int type, Date date, int num) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(type, num);
return new Date(cal.getTime().getTime());
}
/**
* Adds the specified number of Days to the specified Date object
* To subtract the specified number of Days to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 days from the specified date.
*
* @param date Date to be add
* @param numDays Number of days to add
* @return date Added Date
*/
public static Date addDaysToDate(Date date, int numDays) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, numDays);
return c.getTime();
}
/**
* Adds the specified number of Hours to the specified Date object
* To subtract the specified number of hours to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 hours from the specified date.
*
* @param date Date to be add
* @param numHours A valued byte that could possibly be of negative value.
* @return date Added Date
* @since 27/10/2001
*/
public static Date addHoursToDate(Date date, int numHours) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.HOUR_OF_DAY, numHours);
return c.getTime();
}
/**
* Adds the specified number of Minutes to the specified Date object
* To subtract the specified number of Minutes to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 minutes from the specified date.
*
* @param date Date to be add
* @param numMins Number of minutes to add
* @return date Added Date
* @since 27/10/2001
*/
public static Date addMinutesToDate(Date date, int numMins) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MINUTE, numMins);
return c.getTime();
}
/**
* Adds the specified number of Months to the specified Date object
*
* @param date Date to be add
* @param numMonths Number of months to add
* @return date Added Date
*/
public static Date addMonthsToDate(Date date, int numMonths) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, numMonths);
return c.getTime();
}
/**
* Adds the specified number of Years to the specified Date object
*
* @param date Date to be add
* @param numYears Number of years to add
* @return date Added Date
*/
public static Date addYearsToDate(Date date, int numYears) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, numYears);
return c.getTime();
}
/**
* The method will compares 2 dates (excluding the HH MM SS)
*
* @param date1 1st date parameter
* @param date2 2nd date parameter
* @return returns -1 if 1st date parameter is earlier than 2nd date
* parameter retuns 0 if both dates parameter is the same day
* retuns 1 if 1st date parameter is later than 2nd date parameter
*/
public static int compareDates(Date date1, Date date2) {
if ((date1 == null) && (date2 == null)) {
return 0;
}
if (date1 == null) {
return -1;
}
if (date2 == null) {
return 1;
}
String strFormat = "yyyyMMdd";
SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
int intDate1 = Integer.parseInt(dateFormat.format(date1));
int intDate2 = Integer.parseInt(dateFormat.format(date2));
if (intDate1 == intDate2) {
return 0;
}
if (intDate1 > intDate2) {
return 1;
}
return -1;
}
/**
* Parses Date object to formatted string
*
* @param date date to be converted
* @param formatStr Date/Time pattern. Example: ddMMyyyy or HHmmss or any
* other patterns
* @return String in required format Format : dd = Day MM = Month yyyy =
* Year HH = Hour mm = Minute ss = Second All format same as
* SimpleDateFormat. Null is returned if the date object is null.
* @since 22/03/2001
*/
public static String parseDate(Date date, String formatStr) {
SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
if (date == null) {
return null;
} else {
return dateFormat.format(date);
}
}
/**
* Parses Date object to date-time formatted string
*
* @param date THe date to be converted
* @return String in required format. Null is returned if the date object
* is null. (All format same as SimpleDateFormat)
* @since 25/10/2001
*/
public static String parseDate(Date date) {
return parseDate(date, DATETIME_FORMAT);
}
/**
* Resets time fields of date to 00:00
*
* @param date Date to be reset the time to zero
* @return date Converted Date
*/
public static Date resetTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* Converts the specified date-time string to Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @param dateTimeFormat The date pattern in this format 'ddMMyyyy HHmm'
* @return the Date representation. Returns null if the date object or the
* strDateTime or the dateTimeFormat is null.
*/
public static Date toDate(String strDateTime, String dateTimeFormat) {
if ((strDateTime == null) || (strDateTime.length() == 0) ||
(dateTimeFormat == null) || (dateTimeFormat.length() == 0)) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(dateTimeFormat);
Date date = dateFormat.parse(strDateTime, new ParsePosition(0));
if (date == null) {
return null;
}
// String dateStr = parseDate(date, dateTimeFormat);
//
// if (!strDateTime.equals(dateStr)) {
// return null;
// }
return date;
}
/**
* Converts the specified date-time string to Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @return the Date representation. Returns null if the date object or the
* strDateTime or the dateTimeFormat is null.
*/
public static Date toDate(String strDateTime) {
return toDate(strDateTime, DATETIME_FORMAT);
}
/**
* Gets an integer string representation of the specified month.
*
* @param mthMMM Month of three letter string. For example, "JAN",
* "FEB",..
* @return a string number equivalent of the specified month string. If
* the specified month is unknown, zero string is returned that is
* "00".
* @since 27/03/2000
*/
public static String toMMFormat(String mthMMM) {
if (mthMMM.equalsIgnoreCase(MTH_JAN)) {
return "01";
} else if (mthMMM.equalsIgnoreCase(MTH_FEB)) {
return "02";
} else if (mthMMM.equalsIgnoreCase(MTH_MAR)) {
return "03";
} else if (mthMMM.equalsIgnoreCase(MTH_APR)) {
return "04";
} else if (mthMMM.equalsIgnoreCase(MTH_MAY)) {
return "05";
} else if (mthMMM.equalsIgnoreCase(MTH_JUN)) {
return "06";
} else if (mthMMM.equalsIgnoreCase(MTH_JUL)) {
return "07";
} else if (mthMMM.equalsIgnoreCase(MTH_AUG)) {
return "08";
} else if (mthMMM.equalsIgnoreCase(MTH_SEP)) {
return "09";
} else if (mthMMM.equalsIgnoreCase(MTH_OCT)) {
return "10";
} else if (mthMMM.equalsIgnoreCase(MTH_NOV)) {
return "11";
} else if (mthMMM.equalsIgnoreCase(MTH_DEC)) {
return "12";
}
return null;
}
/**
* Gets a specified month string as JAN, FEB..
*
* @param mthMM The month as 2 digits For example, "01", "02",..
* @return a specified month string. If the specified month is unknown,
* empty string ("") is returned.
* @since 27/03/2000
*/
public static String toMMMFormat(String mthMM) {
if ("01".equals(mthMM)) {
return MTH_JAN;
} else if ("02".equals(mthMM)) {
return MTH_FEB;
} else if ("03".equals(mthMM)) {
return MTH_MAR;
} else if ("04".equals(mthMM)) {
return MTH_APR;
} else if ("05".equals(mthMM)) {
return MTH_MAY;
} else if ("06".equals(mthMM)) {
return MTH_JUN;
} else if ("07".equals(mthMM)) {
return MTH_JUL;
} else if ("08".equals(mthMM)) {
return MTH_AUG;
} else if ("09".equals(mthMM)) {
return MTH_SEP;
} else if ("10".equals(mthMM)) {
return MTH_OCT;
} else if ("11".equals(mthMM)) {
return MTH_NOV;
} else if ("12".equals(mthMM)) {
return MTH_DEC;
}
return null;
}
/**
* Converts the specified date-time string to SQL Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @param dateTimeFormat The date pattern in this format 'ddMMyyyy HHmm'
* @return the SQL Date representation. Returns null if the date object or
* the strDateTime or the dateTimeFormat is null.
*/
public static java.sql.Date toSQLDate(String strDateTime,
String dateTimeFormat) {
Date date = toDate(strDateTime, dateTimeFormat);
if (date == null) {
return null;
}
return new java.sql.Date(date.getTime());
}
/**
* Converts the Date object to SQL Date object.
*
* @param date The date to be converted.
* @return the SQL Date representation.
*/
public static java.sql.Date toSQLDate(Date date) {
if (date == null) {
return null;
}
return new java.sql.Date(date.getTime());
}
/**
* Converts the specified date-time string to SQL Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @return the SQL Date representation. Returns null if the date object or
* the strDateTime or the dateTimeFormat is null.
*/
public static java.sql.Date toSQLDate(String strDateTime) {
return toSQLDate(strDateTime, DATETIME_FORMAT);
}
/**
* Converts the specified date-time string to Timestamp.
*
* @param dateTimeStr The String object in this ddMMyyyy HHmm format
* @return Timestamp object. Returns null if dateTimeStr is null Format
* used is meant for Oracle dbs only
*/
public static Timestamp toTimestamp(String dateTimeStr) {
return toTimestamp(toDate(dateTimeStr));
}
/**
* Converts the specified date-time string to Timestamp.
*
* @param dateTimeStr The String object in this ddMMyyyy HHmm format
* @param dateTimeFormat The date pattern in this format 'ddMMyyyy HHmm'
* @return Timestamp object. Returns null if dateTimeStr is null Format
* used is meant for Oracle dbs only
*/
public static Timestamp toTimestamp(String dateTimeStr,
String dateTimeFormat) {
return toTimestamp(toDate(dateTimeStr, dateTimeFormat));
}
/**
* Converts the specified Calendar to Timestamp.
*
* @param date The Date object.
* @return Timestamp object. Returns null if date object is null Format
* used is meant for Oracle dbs only
*/
public static Timestamp toTimestamp(Date date) {
if (date == null) {
return null;
}
return new Timestamp(date.getTime());
}
/**
* Converts the specified Calendar to Timestamp.
*
* @param timeStamp The TimeStamp object.
* @return Date object. Returns null if timestamp object is null Format
* used is meant for Oracle dbs only
*/
public static Date toDate(Timestamp timeStamp) {
if (timeStamp == null) {
return null;
}
return new Date(timeStamp.getTime());
}
/**
* get the target date(s) after(before) a specified period from a marked date
*
* @param originalJobDate the date to start job
* @param months user input to control the the period
* @param days user input to control the the period
* @return expiredDate the date that road tax has expired
*/
public static java.util.Date[] getDurationDates(Date originalJobDate, float months, int days) {
if (originalJobDate == null) {
return null;
}
java.util.Date[] expireDates;
Calendar markedDate = Calendar.getInstance();
markedDate.setTime(originalJobDate);
int iMonths = (int) months;
int iDays = days + Math.round(30 * (months - iMonths));
if (months < 0) {
markedDate.add(Calendar.DATE, iDays);
Calendar tempDate = (Calendar) markedDate.clone();
markedDate.add(Calendar.MONTH, iMonths);
int dayTmp = tempDate.get(Calendar.DATE);
int maxDaysTmp = tempDate.getActualMaximum(Calendar.DATE);
int day = markedDate.get(Calendar.DATE);
int maxDays = markedDate.getActualMaximum(Calendar.DATE);
if (dayTmp > day) {
expireDates = null;
} else if (dayTmp == maxDaysTmp && day < maxDays) {
expireDates = new Date[maxDays - day + 1];
for (int i = 0; i < expireDates.length; i++) {
expireDates[i] = markedDate.getTime();
markedDate.set(Calendar.DATE, ++day);
}
} else {
expireDates = new Date[1];
expireDates[0] = markedDate.getTime();
}
} else {
expireDates = new Date[1];
markedDate.add(Calendar.MONTH, iMonths);
markedDate.add(Calendar.DATE, iDays);
expireDates[0] = markedDate.getTime();
}
return expireDates;
}
/**
* to determine is the date is infinite. ie is the year is 99999.
* 9999 is used to detnote the expiry date does not expire for ever
* Added user : smurali ext : 7943
*
* @param dateToCheck Date the date to check is it infinite
* @return result Boolean if the date is infinity it will return true. or it will return false
*/
public static Boolean isInfinity(Date dateToCheck) {
if (dateToCheck == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(dateToCheck);
int year = cal.get(Calendar.YEAR);
log.info("The date is infinity. The given year :" + year);
if (year >= 9999) {
log.info("The date is infinity");
return new Boolean(true);
}
log.info("The date is not infinity");
return new Boolean(false);
}
}
public static void main(String args[])
{
Calendar cal = Calendar.getInstance();
System.out.println("今天的日期: " + cal.getTime());
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
System.out.println("本周第一天: " + cal.getTime());
cal.add(Calendar.DATE, 6);
System.out.println("本周末: " + cal.getTime());
}
2.如何计算当前时间之前的某个时间点
Calendar cal = Calendar.getInstance();
//当前时期往前推两天
cal.add(Calendar.DATE,-2);
//当前时间往前推两个小时
cal.add(Calendar.HOUR,-2);
//当前时间往前推两个月
cal.add(Calendar.MONTH,-2);
3.一些常用的日期处理
/**
* This DateUtil class provides methods for formatting, validating and
* retrieving different types of dates. <BR><BR> Note: Struts validator also
* provides a similar Date validator, one may use either one of one's
* preference for validating the validility of the date.
*
* @author Framework Team
* @version 1.0
* @class DateUtil
* @since 12/12/2002
*/
public class DateUtil {
/**
* A log instance for this class
*/
protected static Logger log = Logger.getLogger(DateUtil.class.toString());
// Dates constants
/**
* "JAN" to represent January
*/
public static final String MTH_JAN = "Jan";
/**
* "FEB" to represent February
*/
public static final String MTH_FEB = "Feb";
/**
* "MAR" to represent March
*/
public static final String MTH_MAR = "Mar";
/**
* "APR" to represent April
*/
public static final String MTH_APR = "Apr";
/**
* "MAY" to represent May
*/
public static final String MTH_MAY = "May";
/**
* "JUNE" to represent June
*/
public static final String MTH_JUN = "Jun";
/**
* "JUL" to represent July
*/
public static final String MTH_JUL = "Jul";
/**
* "AUG" to represent August
*/
public static final String MTH_AUG = "Aug";
/**
* "SEP" to represent September
*/
public static final String MTH_SEP = "Sep";
/**
* "OCT" to represent October
*/
public static final String MTH_OCT = "Oct";
/**
* "NOV" to represent November
*/
public static final String MTH_NOV = "Nov";
/**
* "DEC" to represent December
*/
public static final String MTH_DEC = "Dec";
/**
* The date pattern in this format 'ddMMyyyy HHmm'
*/
public static String DATETIME_FORMAT = "ddMMyyyy HHmm";
//Add By Xi Wei on 21 Dec 2004
public static String DATE_FORMAT = "dd MMM yyyy";
public static String TIMESTAMP_FORMAT = "dd MMM yyyy HH:mm:ss";
/**
* Returns a date object from input string indicating year, month and day
*
* @param year Year Indicator
* @param month Month indicator, 1=jan 2=feb ...
* @param day Date indicator eg: any day from 1...31.
* @return date java.util.Date object in millisecond.
* @since 15/05/2000
*/
public static Date getDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(year, month - 1, day, 0, 0, 0);
return cal.getTime();
}
/**
* Compares the 2 dates: Returns true if the 2 dates are equal.
*
* @param date1 Date to compare
* @param date2 Date to compare
* @return true if <code>date1</code> equals to <code>date2</code>.
* @since 24/04/2001
*/
public static boolean isDateEqual(Date date1, Date date2) {
if ((date1 == null) || (date2 == null)) {
return false;
}
return resetTime(date1).compareTo(resetTime(date2)) == 0;
}
/**
* Sets the default timezone to the specified timezone ID. Note: The
* system time will remain unchanged. Only the Time zone for the current
* thread is set.
*
* @param timeZoneID The timezone ID. Example: "America/Los_Angeles", "CCT"
* which stands for China/Taiwan = S'pore
*/
public static void setDefaultTimeZone(String timeZoneID) {
TimeZone.setDefault(TimeZone.getTimeZone(timeZoneID));
}
/**
* Calculates the elapsed time between 2 dates. The elapsed time calculated
* could either be in years, months or days
*
* @param type (int) The variable type determines the calculation of the
* elapsed time to be based on either years, months or days. To
* compute the elapsed time in year input type set to Calendar.YEAR
* To compute the elapsed time in month input type set to
* Calendar.MONTH By default the elapsed time will compute in days
* @param startDate start date
* @param endDate end date
* @return the elapsed time (int)
*/
public static final int getElapsedTime(int type, Date startDate,
Date endDate) {
int elapsed = 0;
if ((startDate == null) || (endDate == null)) {
return -1;
}
if (startDate.after(endDate)) {
return -1;
}
GregorianCalendar gc1 = (GregorianCalendar) Calendar.getInstance();
GregorianCalendar gc2 = (GregorianCalendar) gc1.clone();
gc1.setTime(startDate);
gc2.setTime(endDate);
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
if ((type != Calendar.MONTH) && (type != Calendar.YEAR)) {
type = Calendar.DATE;
}
if (type == Calendar.MONTH) {
gc1.clear(Calendar.DATE);
gc2.clear(Calendar.DATE);
}
if (type == Calendar.YEAR) {
gc1.clear(Calendar.DATE);
gc2.clear(Calendar.DATE);
gc1.clear(Calendar.MONTH);
gc2.clear(Calendar.MONTH);
}
while (gc1.before(gc2)) {
gc1.add(type, 1);
elapsed++;
}
return elapsed;
}
/**
* This method will determine if the date is the last day of the month
*
* @param date date
* @return returns true if the date falls on the last day of the month else
* returns false
*/
public static final boolean isEndOfTheMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (cal.get(Calendar.DATE) == maxDay) {
return true;
}
return false;
}
/**
* This method will determine if the date is the last day of the year
*
* @param date date
* @return returns true if the date falls on the last day of the year else
* returns false
*/
public static final boolean isEndOfTheYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if ((cal.get(Calendar.MONTH) == 11) && (cal.get(Calendar.DATE) == 31)) {
return true;
}
return false;
}
/**
* This method will return the last day of the months
*
* @param date date
* @return returns the last day of the month
*/
public static final int getLastDayOfTheMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* Returns the numeric value of the specified month
*
* @param month The 3 letter month representation. Example: "Jan", "Feb", etc
* @return the numeric value of the specified month
*/
public static int getMthInInt(String month) {
if (month.equalsIgnoreCase(MTH_JAN)) {
return 1;
} else if (month.equalsIgnoreCase(MTH_FEB)) {
return 2;
} else if (month.equalsIgnoreCase(MTH_MAR)) {
return 3;
} else if (month.equalsIgnoreCase(MTH_APR)) {
return 4;
} else if (month.equalsIgnoreCase(MTH_MAY)) {
return 5;
} else if (month.equalsIgnoreCase(MTH_JUN)) {
return 6;
} else if (month.equalsIgnoreCase(MTH_JUL)) {
return 7;
} else if (month.equalsIgnoreCase(MTH_AUG)) {
return 8;
} else if (month.equalsIgnoreCase(MTH_SEP)) {
return 9;
} else if (month.equalsIgnoreCase(MTH_OCT)) {
return 10;
} else if (month.equalsIgnoreCase(MTH_NOV)) {
return 11;
} else if (month.equalsIgnoreCase(MTH_DEC)) {
return 12;
} else {
return 0;
}
}
/**
* Return the date of the next working day
*
* @return the date of the next working day
*/
public static Date getNextWorkingDay() {
Date nextWorkingDay = DateUtil.addDaysToDate(DateUtil.getSystemDate(), 1);
Calendar c = Calendar.getInstance();
c.setTime(nextWorkingDay);
int day = c.get(Calendar.DAY_OF_WEEK);
if (day == Calendar.SUNDAY) {
nextWorkingDay = DateUtil.addDaysToDate(nextWorkingDay, 1);
}
return nextWorkingDay;
}
/**
* Compares the 2 dates: Returns true if the start date is before the end
* date.
*
* @param startDate Starting date of a particular time period.
* @param endDate Ending date of a particular time period.
* @return true if the <code>startDate</code> is before
* <code>endDate</code>.
* @since 24/03/2001
*/
public static boolean isStartBeforeEndDate(Date startDate, Date endDate) {
if ((startDate == null) || (endDate == null)) {
return false;
}
return resetTime(startDate).compareTo(resetTime(endDate)) < 0;
}
/**
* This method will determine if the date occurs on the beginning of the
* month
*
* @param date date
* @return returns true if date is on the beginning of the month else
* returns false
*/
public static final boolean isStartOfTheMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (cal.get(Calendar.DATE) == 1) {
return true;
}
return false;
}
/**
* This method will return
* month
*
* @param date date
* @return returns month in int
*/
public static final int getMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.MONTH);
}
public static final int getYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.YEAR);
}
/**
* This method will determine if the date occurs at the beginning of the
* year
*
* @param date date
* @return returns true if the date occurs on the beginning of the year
* else returns false
*/
public static final boolean isStartOfTheYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if ((cal.get(Calendar.MONTH) == 1) && (cal.get(Calendar.DATE) == 1)) {
return true;
}
return false;
}
/**
* Returns the corresponding 3 letter string value of the month specified by numeric month value
*
* @param month The numeric value of the specified month
* @return the corresponding 3 letter string value of the month specified by numeric month value
*/
public static String getStrMth(int month) {
if (month == 1) {
return MTH_JAN;
} else if (month == 2) {
return MTH_FEB;
} else if (month == 3) {
return MTH_MAR;
} else if (month == 4) {
return MTH_APR;
} else if (month == 5) {
return MTH_MAY;
} else if (month == 6) {
return MTH_JUN;
} else if (month == 7) {
return MTH_JUL;
} else if (month == {
return MTH_AUG;
} else if (month == 9) {
return MTH_SEP;
} else if (month == 10) {
return MTH_OCT;
} else if (month == 11) {
return MTH_NOV;
} else if (month == 12) {
return MTH_DEC;
} else {
return "";
}
}
/**
* Calculates the duration in years, months and days.
*
* @param startDate Start Date of a period.
* @param endDate End date of a period.
* @return int [] result [0]=duration in years, [1]=duration in months,
* [2]=duration in days.
*/
public static final int[] computeDuration(Date startDate, Date endDate) {
Calendar from = Calendar.getInstance();
Calendar to = Calendar.getInstance();
from.setTime(startDate);
to.setTime(endDate);
int birthYYYY = from.get(Calendar.YEAR);
int birthMM = from.get(Calendar.MONTH);
int birthDD = from.get(Calendar.DAY_OF_MONTH);
int asofYYYY = to.get(Calendar.YEAR);
int asofMM = to.get(Calendar.MONTH);
int asofDD = to.get(Calendar.DAY_OF_MONTH);
int ageInYears = asofYYYY - birthYYYY;
int ageInMonths = asofMM - birthMM;
int ageInDays = asofDD - birthDD + 1;
if (ageInDays < 0) {
/*
* Guaranteed after this single treatment, ageInDays will be >= 0.
* that is ageInDays = asofDD - birthDD + daysInBirthMM.
*/
ageInDays += from.getActualMaximum(Calendar.DAY_OF_MONTH);
ageInMonths--;
}
if (ageInDays == to.getActualMaximum(Calendar.DAY_OF_MONTH)) {
ageInDays = 0;
ageInMonths++;
}
if (ageInMonths < 0) {
ageInMonths += 12;
ageInYears--;
}
if ((birthYYYY < 0) && (asofYYYY > 0)) {
ageInYears--;
}
if (ageInYears < 0) {
ageInYears = 0;
ageInMonths = 0;
ageInDays = 0;
}
int[] result = new int[3];
result[0] = ageInYears;
result[1] = ageInMonths;
result[2] = ageInDays;
return result;
}
/**
* Returns the current SQL date.
*
* @return Date
*/
public static java.sql.Date getSystemDate() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sysDate = new java.sql.Date(cal.getTime().getTime());
return sysDate;
}
/**
* Returns the current timestamp.
*
* @return Timestamp
*/
public static Timestamp getSystemTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
/**
* Returns true if the length of the year is of 4 digits
*
* @param s String value Year
* @return True if the year length is of 4 digits, False otherwise
* @since 20/04/2001
*/
public static boolean isValidYearFormat(String s) {
if (s == null) {
return false;
} else if (s.trim().length() == 4) {
return true;
}
return false;
}
/**
* This method convert the date to string
*
* @param date date
* @param strFormat the string format
* @return date as string format
*/
public static String getDate(Date date, String strFormat) {
return DateUtil.parseDate(date, strFormat);
}
/**
* Returns true if the String is a valid date.
*
* @param strDate The date in format ddmmyyyy.
* @return True, if it is a valid date. False, otherwise.
*/
public static boolean isValidDate(String strDate) {
return DateUtil.toDate(strDate, "ddMMyyyy") != null;
}
/**
* Returns true if the String is a valid date by specifying the date format to be verified.
*
* @param strDate The date.
* @param dateStrFormat The date format of the specified strDate
* @return True, if it is a valid date. False, otherwise.
*/
public static boolean isValidDate(String strDate, String dateStrFormat) {
return DateUtil.toDate(strDate, dateStrFormat) != null;
}
/**
* Add year, month or day to a date
* To subtract the specified number of Days to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 days from the specified date.
* The same applies to month and year.
*
* @param type (int). Indicates the input num value is in year, month, or
* days. Valid values are Calendar.YEAR, Calendar.MONTH,
* Calendar.DATE
* @param date (java.sql.Date).
* @param num (int). The value to be added to the input date.
* @return java.sql.Date.
*/
public static final Date addDate(int type, Date date, int num) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(type, num);
return new Date(cal.getTime().getTime());
}
/**
* Adds the specified number of Days to the specified Date object
* To subtract the specified number of Days to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 days from the specified date.
*
* @param date Date to be add
* @param numDays Number of days to add
* @return date Added Date
*/
public static Date addDaysToDate(Date date, int numDays) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, numDays);
return c.getTime();
}
/**
* Adds the specified number of Hours to the specified Date object
* To subtract the specified number of hours to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 hours from the specified date.
*
* @param date Date to be add
* @param numHours A valued byte that could possibly be of negative value.
* @return date Added Date
* @since 27/10/2001
*/
public static Date addHoursToDate(Date date, int numHours) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.HOUR_OF_DAY, numHours);
return c.getTime();
}
/**
* Adds the specified number of Minutes to the specified Date object
* To subtract the specified number of Minutes to the specified Date object, juz use a negative number
* Example: DateUtil.addDaysToDate(date, -5) == subtracting 5 minutes from the specified date.
*
* @param date Date to be add
* @param numMins Number of minutes to add
* @return date Added Date
* @since 27/10/2001
*/
public static Date addMinutesToDate(Date date, int numMins) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MINUTE, numMins);
return c.getTime();
}
/**
* Adds the specified number of Months to the specified Date object
*
* @param date Date to be add
* @param numMonths Number of months to add
* @return date Added Date
*/
public static Date addMonthsToDate(Date date, int numMonths) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, numMonths);
return c.getTime();
}
/**
* Adds the specified number of Years to the specified Date object
*
* @param date Date to be add
* @param numYears Number of years to add
* @return date Added Date
*/
public static Date addYearsToDate(Date date, int numYears) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, numYears);
return c.getTime();
}
/**
* The method will compares 2 dates (excluding the HH MM SS)
*
* @param date1 1st date parameter
* @param date2 2nd date parameter
* @return returns -1 if 1st date parameter is earlier than 2nd date
* parameter retuns 0 if both dates parameter is the same day
* retuns 1 if 1st date parameter is later than 2nd date parameter
*/
public static int compareDates(Date date1, Date date2) {
if ((date1 == null) && (date2 == null)) {
return 0;
}
if (date1 == null) {
return -1;
}
if (date2 == null) {
return 1;
}
String strFormat = "yyyyMMdd";
SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
int intDate1 = Integer.parseInt(dateFormat.format(date1));
int intDate2 = Integer.parseInt(dateFormat.format(date2));
if (intDate1 == intDate2) {
return 0;
}
if (intDate1 > intDate2) {
return 1;
}
return -1;
}
/**
* Parses Date object to formatted string
*
* @param date date to be converted
* @param formatStr Date/Time pattern. Example: ddMMyyyy or HHmmss or any
* other patterns
* @return String in required format Format : dd = Day MM = Month yyyy =
* Year HH = Hour mm = Minute ss = Second All format same as
* SimpleDateFormat. Null is returned if the date object is null.
* @since 22/03/2001
*/
public static String parseDate(Date date, String formatStr) {
SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
if (date == null) {
return null;
} else {
return dateFormat.format(date);
}
}
/**
* Parses Date object to date-time formatted string
*
* @param date THe date to be converted
* @return String in required format. Null is returned if the date object
* is null. (All format same as SimpleDateFormat)
* @since 25/10/2001
*/
public static String parseDate(Date date) {
return parseDate(date, DATETIME_FORMAT);
}
/**
* Resets time fields of date to 00:00
*
* @param date Date to be reset the time to zero
* @return date Converted Date
*/
public static Date resetTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* Converts the specified date-time string to Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @param dateTimeFormat The date pattern in this format 'ddMMyyyy HHmm'
* @return the Date representation. Returns null if the date object or the
* strDateTime or the dateTimeFormat is null.
*/
public static Date toDate(String strDateTime, String dateTimeFormat) {
if ((strDateTime == null) || (strDateTime.length() == 0) ||
(dateTimeFormat == null) || (dateTimeFormat.length() == 0)) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(dateTimeFormat);
Date date = dateFormat.parse(strDateTime, new ParsePosition(0));
if (date == null) {
return null;
}
// String dateStr = parseDate(date, dateTimeFormat);
//
// if (!strDateTime.equals(dateStr)) {
// return null;
// }
return date;
}
/**
* Converts the specified date-time string to Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @return the Date representation. Returns null if the date object or the
* strDateTime or the dateTimeFormat is null.
*/
public static Date toDate(String strDateTime) {
return toDate(strDateTime, DATETIME_FORMAT);
}
/**
* Gets an integer string representation of the specified month.
*
* @param mthMMM Month of three letter string. For example, "JAN",
* "FEB",..
* @return a string number equivalent of the specified month string. If
* the specified month is unknown, zero string is returned that is
* "00".
* @since 27/03/2000
*/
public static String toMMFormat(String mthMMM) {
if (mthMMM.equalsIgnoreCase(MTH_JAN)) {
return "01";
} else if (mthMMM.equalsIgnoreCase(MTH_FEB)) {
return "02";
} else if (mthMMM.equalsIgnoreCase(MTH_MAR)) {
return "03";
} else if (mthMMM.equalsIgnoreCase(MTH_APR)) {
return "04";
} else if (mthMMM.equalsIgnoreCase(MTH_MAY)) {
return "05";
} else if (mthMMM.equalsIgnoreCase(MTH_JUN)) {
return "06";
} else if (mthMMM.equalsIgnoreCase(MTH_JUL)) {
return "07";
} else if (mthMMM.equalsIgnoreCase(MTH_AUG)) {
return "08";
} else if (mthMMM.equalsIgnoreCase(MTH_SEP)) {
return "09";
} else if (mthMMM.equalsIgnoreCase(MTH_OCT)) {
return "10";
} else if (mthMMM.equalsIgnoreCase(MTH_NOV)) {
return "11";
} else if (mthMMM.equalsIgnoreCase(MTH_DEC)) {
return "12";
}
return null;
}
/**
* Gets a specified month string as JAN, FEB..
*
* @param mthMM The month as 2 digits For example, "01", "02",..
* @return a specified month string. If the specified month is unknown,
* empty string ("") is returned.
* @since 27/03/2000
*/
public static String toMMMFormat(String mthMM) {
if ("01".equals(mthMM)) {
return MTH_JAN;
} else if ("02".equals(mthMM)) {
return MTH_FEB;
} else if ("03".equals(mthMM)) {
return MTH_MAR;
} else if ("04".equals(mthMM)) {
return MTH_APR;
} else if ("05".equals(mthMM)) {
return MTH_MAY;
} else if ("06".equals(mthMM)) {
return MTH_JUN;
} else if ("07".equals(mthMM)) {
return MTH_JUL;
} else if ("08".equals(mthMM)) {
return MTH_AUG;
} else if ("09".equals(mthMM)) {
return MTH_SEP;
} else if ("10".equals(mthMM)) {
return MTH_OCT;
} else if ("11".equals(mthMM)) {
return MTH_NOV;
} else if ("12".equals(mthMM)) {
return MTH_DEC;
}
return null;
}
/**
* Converts the specified date-time string to SQL Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @param dateTimeFormat The date pattern in this format 'ddMMyyyy HHmm'
* @return the SQL Date representation. Returns null if the date object or
* the strDateTime or the dateTimeFormat is null.
*/
public static java.sql.Date toSQLDate(String strDateTime,
String dateTimeFormat) {
Date date = toDate(strDateTime, dateTimeFormat);
if (date == null) {
return null;
}
return new java.sql.Date(date.getTime());
}
/**
* Converts the Date object to SQL Date object.
*
* @param date The date to be converted.
* @return the SQL Date representation.
*/
public static java.sql.Date toSQLDate(Date date) {
if (date == null) {
return null;
}
return new java.sql.Date(date.getTime());
}
/**
* Converts the specified date-time string to SQL Date object based on the
* specified date-time format. <CODE>null</CODE> is returned if the
* specified date is invalid.
*
* @param strDateTime The date string in this format 'ddMMyyyy HHmm'.
* @return the SQL Date representation. Returns null if the date object or
* the strDateTime or the dateTimeFormat is null.
*/
public static java.sql.Date toSQLDate(String strDateTime) {
return toSQLDate(strDateTime, DATETIME_FORMAT);
}
/**
* Converts the specified date-time string to Timestamp.
*
* @param dateTimeStr The String object in this ddMMyyyy HHmm format
* @return Timestamp object. Returns null if dateTimeStr is null Format
* used is meant for Oracle dbs only
*/
public static Timestamp toTimestamp(String dateTimeStr) {
return toTimestamp(toDate(dateTimeStr));
}
/**
* Converts the specified date-time string to Timestamp.
*
* @param dateTimeStr The String object in this ddMMyyyy HHmm format
* @param dateTimeFormat The date pattern in this format 'ddMMyyyy HHmm'
* @return Timestamp object. Returns null if dateTimeStr is null Format
* used is meant for Oracle dbs only
*/
public static Timestamp toTimestamp(String dateTimeStr,
String dateTimeFormat) {
return toTimestamp(toDate(dateTimeStr, dateTimeFormat));
}
/**
* Converts the specified Calendar to Timestamp.
*
* @param date The Date object.
* @return Timestamp object. Returns null if date object is null Format
* used is meant for Oracle dbs only
*/
public static Timestamp toTimestamp(Date date) {
if (date == null) {
return null;
}
return new Timestamp(date.getTime());
}
/**
* Converts the specified Calendar to Timestamp.
*
* @param timeStamp The TimeStamp object.
* @return Date object. Returns null if timestamp object is null Format
* used is meant for Oracle dbs only
*/
public static Date toDate(Timestamp timeStamp) {
if (timeStamp == null) {
return null;
}
return new Date(timeStamp.getTime());
}
/**
* get the target date(s) after(before) a specified period from a marked date
*
* @param originalJobDate the date to start job
* @param months user input to control the the period
* @param days user input to control the the period
* @return expiredDate the date that road tax has expired
*/
public static java.util.Date[] getDurationDates(Date originalJobDate, float months, int days) {
if (originalJobDate == null) {
return null;
}
java.util.Date[] expireDates;
Calendar markedDate = Calendar.getInstance();
markedDate.setTime(originalJobDate);
int iMonths = (int) months;
int iDays = days + Math.round(30 * (months - iMonths));
if (months < 0) {
markedDate.add(Calendar.DATE, iDays);
Calendar tempDate = (Calendar) markedDate.clone();
markedDate.add(Calendar.MONTH, iMonths);
int dayTmp = tempDate.get(Calendar.DATE);
int maxDaysTmp = tempDate.getActualMaximum(Calendar.DATE);
int day = markedDate.get(Calendar.DATE);
int maxDays = markedDate.getActualMaximum(Calendar.DATE);
if (dayTmp > day) {
expireDates = null;
} else if (dayTmp == maxDaysTmp && day < maxDays) {
expireDates = new Date[maxDays - day + 1];
for (int i = 0; i < expireDates.length; i++) {
expireDates[i] = markedDate.getTime();
markedDate.set(Calendar.DATE, ++day);
}
} else {
expireDates = new Date[1];
expireDates[0] = markedDate.getTime();
}
} else {
expireDates = new Date[1];
markedDate.add(Calendar.MONTH, iMonths);
markedDate.add(Calendar.DATE, iDays);
expireDates[0] = markedDate.getTime();
}
return expireDates;
}
/**
* to determine is the date is infinite. ie is the year is 99999.
* 9999 is used to detnote the expiry date does not expire for ever
* Added user : smurali ext : 7943
*
* @param dateToCheck Date the date to check is it infinite
* @return result Boolean if the date is infinity it will return true. or it will return false
*/
public static Boolean isInfinity(Date dateToCheck) {
if (dateToCheck == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(dateToCheck);
int year = cal.get(Calendar.YEAR);
log.info("The date is infinity. The given year :" + year);
if (year >= 9999) {
log.info("The date is infinity");
return new Boolean(true);
}
log.info("The date is not infinity");
return new Boolean(false);
}
}
发表评论
-
java模拟点击
2020-05-12 18:26 349try { Dimension screenS ... -
jekins集成maven发布项目过程中遇到的坑
2017-04-05 14:33 1647背景: 用maven构建项目之后,每次需要部署集成测试环 ... -
logback配置
2015-08-17 15:30 626<?xml version="1.0" ... -
javamail
2014-07-09 21:35 716http://blog.csdn.net/zapldy/art ... -
jdbc批量插入数据
2013-11-10 11:35 815以下过程网上看到,备份一下语法而已 Connection co ... -
jdbc获得生成记录主键
2013-11-10 11:18 666在网上看到的,备份一下而已 Connection conn = ... -
jdbc调用存储过程
2013-11-10 11:12 629只是把调用过程备份一下 Connection conn = ... -
十六进制转字符串
2013-07-04 22:09 1295记录一下十六进制转字符串,以备以后使用方便 //十六进制转字符 ... -
模拟自动登录并发表日志
2012-12-11 20:11 1169公司要求每天都需要写 ... -
List.toArray()强转对象数组
2012-06-13 15:18 1437假设现在有一个集合list,里面装的都是对象A,如下代码进行强 ... -
正则表达式
2012-06-05 13:53 1如果你曾经用过Perl或任 ... -
关于LinkedHashMap的一些简单实验
2012-05-15 14:53 889同为实现了Map接口的类,LinedHashMap在迭代的时候 ... -
UUID
2012-05-14 15:34 1443转自http://popwang.iteye.com/blog ... -
eclipse install memory analyzer
2012-05-02 16:16 1042安装地址 http://download.eclipse.or ... -
java加密解密算法记录
2012-04-13 14:56 9862以下内容均摘自我买的书籍《java加密与解密的艺术》作者 梁栋 ... -
common email发送邮件
2012-03-06 16:56 1580项目地址:http://commons.apache.org/ ... -
java实现压缩和解压缩
2012-03-01 16:17 1072转自于站内兄弟的文章:http://wallimn.iteye ... -
java算法记录
2012-02-07 19:12 804package com.algorithm; impor ... -
java中yield(),sleep()以及wait()的区别
2012-02-07 10:30 956转自http://xiechengfa.iteye.com/b ... -
oracle调用java
2011-12-27 15:18 1423修改别人写的oracle数据库调用java代码,换了一个环境, ...
相关推荐
Java日期程序案例(日历,获取当前日期方法、日期查询、日期比较,日期判断);Java日期程序案例(日历,获取当前日期方法、日期查询、日期比较,日期判断);Java日期程序案例(日历,获取当前日期方法、日期查询、...
java日期类函数方法整理 各种日期类函数方法。
JAVA中常见日期判断方法,比如:是否为润年? 获取指定年月的天数等等.
java处理日期合并
将java的日期转换成中文的日期,可以直接使用的源文件。
JAVA处理日期时间常用方法.JAVA处理日期时间常用方法: java.util.Calendar
Java语言深入--Java中日期的使用方法 Java语言深入--Java中日期的使用方法
Java DateUtil.java日期时间操作类源代码,DateUtil类包含了标准的时间和日期格式,以及这些格式在字符串及日期之间转换的方法。比如日期格式转换成时间戳、得到格式化后的系统当前日期、转化日期格式"MM/dd/YY、MM....
日期操作类 Long转日期 字符串毫秒转日期 格式化日期转换方法,年 月 日 时 分 秒 把格式化的日期补全 把格式化的日期转化为毫秒 获取当天凌晨,夜间整点时间毫秒 校验日期是否合法 得到n天之后的日期 得到n天之后是...
java中关于日期处理的总结,包含各种日期格式之间的转java.util.Date(已经不提倡使用,该类的方法比较少) java.util.Calendar(抽象类) java.util.GregorianCalendar(是Calendar的子类,日期处理时候经常使用该类)****...
java日期的使用介绍和具体实现的示例 (适合新手) 1.计算某一月份的最大天数 Calendar time=Calendar.getInstance(); time.clear(); time.set(Calendar.YEAR,year); time.set(Calendar.MONTH,i-1);//注意,Calendar...
java 时间日期帮助类 多达50个实用方法,你想到的,想不到的都有了。 j2ee精英团队10年精华大放送。
Java日期类,可进行日期比较(可精确到分钟)、求几天前、几天后的日期
Java获取各种日期的函数(方法).docx
详细介绍了Java8日期时间相关的api,列举了一些常用的方法,包含java.time、java.time.temporal、java.time.format包下的类和接口操作
java日期选择器。使用之前请把datepicker.jar导入classpath中 使用方法如下: DatePicker datepick = new DatePicker(); 或者 datepick = new DatePicker(date,DefaultFormat,font,dimension);//自定义参数值 //各...
这是我自己总结出来的 java根据当前日期+指定天数(月份...)得到相应日期以及计算两日期之差,希望对大家带来帮助
NULL 博文链接:https://wangyispider.iteye.com/blog/1136731
java格式化日期工具类,不用再重写格式化日期方法。