标签:
public static String getStartEndDate(String aDay, int type) { SimpleDateFormat df = new SimpleDateFormat("yyyy年M月d日");// ("yyyy-MM-dd H:m:s"); Calendar ca = Calendar.getInstance(); try { ca.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(aDay)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Date date1 = null, date2 = null; if (type == 0) { int dayOfWeek = ca.get(Calendar.DAY_OF_WEEK); // 中国习惯:周一是一周的开始 if (dayOfWeek == 1) { dayOfWeek = 7; } else { dayOfWeek--; } System.out.println(("tag" + "dayofweek=" + dayOfWeek + "min= " + ca.getActualMinimum(Calendar.DAY_OF_WEEK) + " max=" + ca .getActualMaximum(Calendar.DAY_OF_WEEK))); Calendar cal = (Calendar) ca.clone(); cal.add(Calendar.DATE, 1 - dayOfWeek); date1 = cal.getTime(); cal = (Calendar) ca.clone(); cal.add(Calendar.DATE, 7 - dayOfWeek); date2 = cal.getTime(); } else if (type == 1) { int maximum = ca.getActualMaximum(Calendar.DAY_OF_MONTH); int minmum = ca.getActualMinimum(Calendar.DAY_OF_MONTH); int day = ca.get(Calendar.DAY_OF_MONTH); Calendar cal = (Calendar) ca.clone(); cal.add(Calendar.DATE, minmum - day); date1 = cal.getTime(); cal = (Calendar) ca.clone(); cal.add(Calendar.DATE,maximum - day); date2 = cal.getTime(); } String str1 = df.format(date1); String str2 = df.format(date2); System.out.println("tag" + "date1=" + str1 + " date2=" + str2); return str1 + "--" + str2; }
这几天在研究字符串与指定类型的转换,阴差阳错地研究起 java 的日期应用了,记录下来,希望你有帮助。
/** * <p>Parses a string representing a date by trying a variety of different parsers.
* * <p>The parse will try each parse pattern in turn. * A parse is only deemed successful if it parses the whole of the input string. * If no parse patterns match, a ParseException is thrown.
* * @param str the date to parse, not null * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null * @param lenient Specify whether or not date/time parsing is to be lenient. * @return the parsed date * @throws IllegalArgumentException if the date string or pattern array is null * @throws ParseException if none of the date patterns were suitable * @see java.util.Calender#isLenient() */ private static Date parseDateWithLeniency( String str, String[] parsePatterns, boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } SimpleDateFormat parser = new SimpleDateFormat(); parser.setLenient(lenient); ParsePosition pos = new ParsePosition(0); for (String parsePattern : parsePatterns) { String pattern = parsePattern; // LANG-530 - need to make sure ‘ZZ‘ output doesn‘t get passed to SimpleDateFormat if (parsePattern.endsWith("ZZ")) { pattern = pattern.substring(0, pattern.length() - 1); } parser.applyPattern(pattern); pos.setIndex(0); String str2 = str; // LANG-530 - need to make sure ‘ZZ‘ output doesn‘t hit SimpleDateFormat as it will ParseException if (parsePattern.endsWith("ZZ")) { str2 = str.replaceAll("([-+][0-9][0-9]):([0-9][0-9])$", "$1$2"); } Date date = parser.parse(str2, pos); if (date != null && pos.getIndex() == str2.length()) { return date; } } throw new ParseException("Unable to parse the date: " + str, -1); } 在 java 日期格式里,"ZZ" 代表的是 时区。在java 里,格式化需要借助类 Formate,同时,parse 的时候一般需要借助类 parsePosition,ParsePosition 是 Format 及其子类所使用的简单类,用来在解析过程中跟踪当前位置。各种 Format 类中的 parseObject 方法要求将 ParsePosition对象作为一个变量。 Calendar 有两种解释日历字段的模式,即 lenient 和 non-lenient。当 Calendar 处于 lenient 模式时,它可接受比它所生成的日历字段范围更大范围内的值。当 Calendar 重新计算日历字段值,以便由 get() 返回这些值时,所有日历字段都被标准化。例如,lenient 模式下的GregorianCalendar 将MONTH == JANUARY、DAY_OF_MONTH == 32 解释为 February 1。
当 Calendar 处于 non-lenient 模式时,如果其日历字段中存在任何不一致性,它都会抛出一个异常。例如,GregorianCalendar 总是在 1 与月份的长度之间生成 DAY_OF_MONTH 值。如果已经设置了任何超出范围的字段值,那么在计算时间或日历字段值时,处于 non-lenient 模式下的GregorianCalendar会抛出一个异常。(在 non-lenient状态下,可以用来检测用户输入的日期是否合法)
private static Date set(Date date, int calendarField, int amount) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } // getInstance() returns a new object, so this method is thread safe. Calendar c = Calendar.getInstance(); c.setLenient(false);// 这里使用严格模式,要求设置日期的值必须正确 c.setTime(date); c.set(calendarField, amount); return c.getTime(); } |
private static Date add(Date date, int calendarField, int amount) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); c.add(calendarField, amount); return c.getTime(); } |
private static Date roll(Date date, int calendarField, int amount) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); c.roll(calendarField, amount); return c.getTime(); }
public static Date setMinutes(Date date, int amount) { return set(date, Calendar.MINUTE, amount); } |
public static Date getFirstDateOfWeek(Date date){ Calendar c = Calendar.getInstance(); c.setTime(date); // 获取本周第一天的值 int firstDayOfWeek = c.getFirstDayOfWeek(); // 当前日期是本周的第几天 int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); int day_diff = 1;//天数差的绝对值,20140901~20140903 天数差为3 if (firstDayOfWeek < dayOfWeek) { day_diff = Math.abs(dayOfWeek-firstDayOfWeek) + 1; } c.add(Calendar.DATE,1-day_diff); return c.getTime(); } |
public static Date getLastDateOfWeek(Date date){ Calendar c = Calendar.getInstance(); c.setTime(date); // 获取本周第一天的值 int firstDayOfWeek = c.getFirstDayOfWeek(); // 当前日期是本周的第几天 int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); int day_diff = 1;//天数差的绝对值 if (firstDayOfWeek < dayOfWeek) { day_diff =Math.abs(dayOfWeek - firstDayOfWeek) + 1; } c.add(Calendar.DATE, 7-day_diff); return c.getTime(); }getActualMaximum(int field) 给定此 Calendar 的时间值,返回指定日历字段可能拥有的最大值。getActualMinimum(int field) 给定此 Calendar 的时间值,返回指定日历字段可能拥有的最小值。借助这两个函数,我们可以获取一天所在月的第一天/最后一天的日期。方法如下:public static Date getFirstDateOfMonth(Date date){ if (date == null) { throw new IllegalArgumentException("the date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); // get the min date in this month int min_day = c.getActualMinimum(Calendar.DATE); c.set(Calendar.DATE, min_day); return c.getTime(); } public static Date getLastDateOfMonth(Date date){ if (date == null) { throw new IllegalArgumentException("the date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); //get the max date in the month int max_day = c.getActualMaximum(Calendar.DATE); c.set(Calendar.DATE, max_day); return c.getTime(); }
public static Date getFirstDateOfWeek(Date date){ Calendar c = Calendar.getInstance(); c.setTime(date);// // 获取本周第一天的值// int firstDayOfWeek = c.getFirstDayOfWeek();// // 当前日期是本周的第几天// int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);// // int day_diff = 1;//天数差的绝对值,20140901~20140903 天数差为3// // if (firstDayOfWeek < dayOfWeek) {// day_diff = Math.abs(dayOfWeek-firstDayOfWeek) + 1;// }// // c.add(Calendar.DATE,1-day_diff); int min_day = c.getActualMinimum(Calendar.DAY_OF_WEEK); c.set(Calendar.DAY_OF_WEEK,min_day); return c.getTime(); } |
private static final int[] seasonFirstMonth = new int[] { 0, 0, 0, 3, 3, 3, 6, 6, 6, 9, 9, 9 }; private static final int[] seasonLastMonth = new int[] { 2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11 }; public static Date getFirstDateOfSeason(Date date){ if (date == null) { throw new IllegalArgumentException("the date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.MONTH, seasonFirstMonth[c.get(Calendar.MONTH)]); c.set(Calendar.DATE, c.getActualMinimum(Calendar.DATE)); return c.getTime(); } public static Date getLastDateOfSeason(Date date){ if (date == null) { throw new IllegalArgumentException("the date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.MONTH, seasonLastMonth[c.get(Calendar.MONTH)]); c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE)); return c.getTime(); } |
public static long getDaysBetweenTwoDate(Date date1,Date date2){ if (date1 == null || date2 == null) { throw new IllegalArgumentException("date1 and date2 must not be null"); } Calendar c1 = Calendar.getInstance(); c1.setTime(date1); Calendar c2 = Calendar.getInstance(); c2.setTime(date2); long mills_one_day = 60 * 60 * 24 * 1000; return Math.abs(c1.getTimeInMillis() - c2.getTimeInMillis())/mills_one_day + 1; } 附:通过阅读 Java API,借助一些基础的推算逻辑,我们可以合成很多很有用工具类,让我们彼此一起努力。在这一次学习当中,本人更感兴趣的,如何通过指定的字符串格式构造指定的对象(如通过字符串构造日期),又如何通过指定格式输出制定对象(如根据 yyyyMMdd 格式输出 日期对象)。获取周 星期 的第一天 最后一天 或者 月的 日期(字符串转日期,日期转字符串,日期加减)
标签:
原文地址:http://www.cnblogs.com/bigben0123/p/5462155.html