- 浏览: 606057 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
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 476try { Dimension screenS ... -
jekins集成maven发布项目过程中遇到的坑
2017-04-05 14:33 1726背景: 用maven构建项目之后,每次需要部署集成测试环 ... -
logback配置
2015-08-17 15:30 667<?xml version="1.0" ... -
javamail
2014-07-09 21:35 820http://blog.csdn.net/zapldy/art ... -
jdbc批量插入数据
2013-11-10 11:35 863以下过程网上看到,备份一下语法而已 Connection co ... -
jdbc获得生成记录主键
2013-11-10 11:18 719在网上看到的,备份一下而已 Connection conn = ... -
jdbc调用存储过程
2013-11-10 11:12 680只是把调用过程备份一下 Connection conn = ... -
十六进制转字符串
2013-07-04 22:09 1373记录一下十六进制转字符串,以备以后使用方便 //十六进制转字符 ... -
模拟自动登录并发表日志
2012-12-11 20:11 1218公司要求每天都需要写 ... -
List.toArray()强转对象数组
2012-06-13 15:18 1510假设现在有一个集合list,里面装的都是对象A,如下代码进行强 ... -
正则表达式
2012-06-05 13:53 1如果你曾经用过Perl或任 ... -
关于LinkedHashMap的一些简单实验
2012-05-15 14:53 932同为实现了Map接口的类,LinedHashMap在迭代的时候 ... -
UUID
2012-05-14 15:34 1497转自http://popwang.iteye.com/blog ... -
eclipse install memory analyzer
2012-05-02 16:16 1108安装地址 http://download.eclipse.or ... -
java加密解密算法记录
2012-04-13 14:56 9928以下内容均摘自我买的书籍《java加密与解密的艺术》作者 梁栋 ... -
common email发送邮件
2012-03-06 16:56 1621项目地址:http://commons.apache.org/ ... -
java实现压缩和解压缩
2012-03-01 16:17 1119转自于站内兄弟的文章:http://wallimn.iteye ... -
java算法记录
2012-02-07 19:12 849package com.algorithm; impor ... -
java中yield(),sleep()以及wait()的区别
2012-02-07 10:30 1006转自http://xiechengfa.iteye.com/b ... -
oracle调用java
2011-12-27 15:18 1484修改别人写的oracle数据库调用java代码,换了一个环境, ...
相关推荐
"JAVA日期判断方法小结" 在JAVA语言中,日期判断是非常重要的一部分,以下是常见的日期判断方法的总结: 1. 判断某年是否为润年 判断某年是否为润年是日期判断的基本方法之一。该方法可以使用以下代码实现: ```...
Java日期程序案例(日历,获取当前日期方法、日期查询、日期比较,日期判断);Java日期程序案例(日历,获取当前日期方法、日期查询、日期比较,日期判断);Java日期程序案例(日历,获取当前日期方法、日期查询、...
根据给定的文件信息,以下是对Java日期类函数方法的详细整理与解释: ### Java日期类函数方法概览 在Java中,处理日期和时间主要依赖于`java.util.Date`、`java.text.SimpleDateFormat`、`java.sql.Date`、`java....
### JAVA日期与字符串的转换 在Java编程中,经常需要将日期对象转化为字符串形式以便于存储或显示,或者反过来将字符串转化成日期对象来进行日期计算等操作。本文将详细介绍如何在Java中实现这两种转换。 #### 一...
### Java日期格式转换详解 在Java开发中,对日期和时间进行操作是非常常见的需求之一。本文将基于给定文件中的代码示例,详细介绍如何在Java中实现日期格式的转换,并探讨其中涉及的关键知识点。 #### 一、理解...
本文详细介绍了如何使用Java处理日期合并的问题,通过对`TimeoffDateDTO`类的定义和日期合并算法的具体实现,提供了一种有效的方法来解决实际工作中经常遇到的时间段重叠问题。这种方法不仅适用于员工请假时间的管理...
本文将重点讲解Java日期的常用操作方法,主要基于提供的`JavaDateUtil.java`文件,假设这是一个自定义的日期工具类。 首先,我们来了解`java.util.Date`。这个类在早期的Java版本中被广泛使用,但它的API设计并不...
将java的日期转换成中文的日期,可以直接使用的源文件。
这篇博客"Java日期转换"探讨了如何在Java中有效地转换和操作日期。Java提供了多种类库来支持日期和时间的操作,包括`java.util.Date`、`java.text.SimpleDateFormat`、`java.time`包中的类等。本文将详细讲解这些类...
如果这个文件包含了代码示例,你可以打开查看具体实现,进一步学习和理解Java日期时间操作的细节。 总之,理解和熟练掌握Java的日期时间操作对于开发人员来说至关重要,无论是在处理用户输入、记录日志还是进行复杂...
然而,java.util.Date 类并不能直接满足日期格式转换的需求,因此需要使用其他类和方法来实现日期格式转换。 本文将介绍如何使用 Java 实现日期格式转换,包括使用 Calendar 类和 SimpleDateFormat 类来格式化日期...
在这个Java 日期帮助类中,包含了多达50个实用方法,涵盖了日期和时间的各种操作,旨在简化开发人员的工作,提高代码的可读性和可维护性。这个类可能是由一个经验丰富的j2ee精英团队经过10年的实践和完善提炼出来的...
以下是一些关于“java日期和查询数据库生成XML文件类”的核心知识点: 1. **Java日期处理**: - `java.time`包:Java 8引入的新时间日期API,提供了`LocalDate`, `LocalTime`, `LocalDateTime`等类,它们提供了...
### Java日期处理大全:掌握时间的艺术 在Java编程中,日期和时间的处理是不可或缺的一部分,尤其是在涉及到数据记录、时间戳、定时任务等场景时。本文将深入探讨Java中的日期处理技术,涵盖从基础到进阶的各种技巧...
Java 日期算法大全 Java 中日期类操作算法大全是 Java ...Java 日期算法大全涵盖了日期类的基本操作、日期类的加减、日期类的格式化输出、日期类的计算等多个方面的知识点,为开发者提供了详细的Java日期算法指南。
本文将深入探讨Java中日期格式化的常用方法,主要关注`SimpleDateFormat`和`java.time`包下的`DateTimeFormatter`。 首先,`SimpleDateFormat`是旧版日期时间API的一部分,尽管在Java 8之后被推荐使用新的`java....
Java 日期格式转换 Java 中日期格式转换是一个常见的问题,在编程中,我们经常需要将字符串转换为日期对象,或者将日期对象转换为字符串。下面,我们将详细讨论 Java 中日期格式转换的知识点。 字符串转换为 java....
### Java日期做差 在Java编程中,处理日期和时间是一个常见需求,尤其是在需要计算两个日期之间的差异时。本文将详细介绍如何使用Java内置的方法来计算两个日期之间的秒数差值以及将这个差值转换为更易读的格式(如...
### Java设置日期格式详解 #### 一、简介 在Java编程中,经常需要处理与日期相关的数据。为了更好地展示和操作这些数据,Java提供了一系列工具类来帮助开发者完成任务。其中,`SimpleDateFormat` 类是 `java.text`...
Java中的日期和时间处理是程序开发中常见的任务,涉及到各种日期和时间的计算、格式化以及比较等操作。在Java中,主要使用`java.util.Date`、`java.util.Calendar`和`java.text.SimpleDateFormat`这三个核心类来处理...