Java Code Examples for java.util.Calendar#WEEK_OF_YEAR

The following examples show how to use java.util.Calendar#WEEK_OF_YEAR . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: AsuraFramework   File: DateUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static int translate(final IntervalUnit unit) {
	switch (unit) {
	case DAY:
		return Calendar.DAY_OF_YEAR;
	case HOUR:
		return Calendar.HOUR_OF_DAY;
	case MINUTE:
		return Calendar.MINUTE;
	case MONTH:
		return Calendar.MONTH;
	case SECOND:
		return Calendar.SECOND;
	case MILLISECOND:
		return Calendar.MILLISECOND;
	case WEEK:
		return Calendar.WEEK_OF_YEAR;
	case YEAR:
		return Calendar.YEAR;
	default:
		throw new IllegalArgumentException("Unknown IntervalUnit");
	}
}
 
Example 2
public void set(final int field, final Integer value) {
    if (value == UNSPECIFIED_VALUE) {
        if (field == Calendar.YEAR) {
            unspecifiedFields.add(Calendar.YEAR);
        } else if (field == Calendar.MONTH) {
            unspecifiedFields.add(Calendar.MONTH);
        } else if (field >= Calendar.WEEK_OF_YEAR && field <= Calendar.DAY_OF_WEEK_IN_MONTH) {
            unspecifiedFields.add(Calendar.DATE);
        } else if (field >= Calendar.HOUR && field <= Calendar.HOUR_OF_DAY) {
            unspecifiedFields.add(Calendar.HOUR_OF_DAY);
        } else if (field == Calendar.MINUTE) {
            unspecifiedFields.add(Calendar.MINUTE);
        }

        // do nothing with other fields

    } else {
        unspecifiedFields.remove(field);
        c.set(field, value);
    }
}
 
Example 3
/** Maps the name of the unit to an integer unit identifier of {@link Calendar} */
private int mapUnitNameToIndex(String unit) {
	switch (unit) {
		case ExpressionParserConstants.DATE_UNIT_YEAR:
			return Calendar.YEAR;
		case ExpressionParserConstants.DATE_UNIT_MONTH:
			return Calendar.MONTH;
		case ExpressionParserConstants.DATE_UNIT_WEEK:
			return Calendar.WEEK_OF_YEAR;
		case ExpressionParserConstants.DATE_UNIT_DAY:
			return Calendar.DAY_OF_MONTH;

		case ExpressionParserConstants.DATE_UNIT_HOUR:
			return Calendar.HOUR_OF_DAY;
		case ExpressionParserConstants.DATE_UNIT_MINUTE:
			return Calendar.MINUTE;
		case ExpressionParserConstants.DATE_UNIT_SECOND:
			return Calendar.SECOND;
		case ExpressionParserConstants.DATE_UNIT_MILLISECOND:
			return Calendar.MILLISECOND;
		default:
			throw new FunctionInputException("expression_parser.function_wrong_type_at", getFunctionName(),
					"unit constant", "third");
	}
}
 
Example 4
public static int convertUnitString(String unit)
{
  int result = 0;
  if (MILLISECONDS.equalsIgnoreCase(unit))
  {
    result = Calendar.MILLISECOND;
  }
  else if (SECONDS.equalsIgnoreCase(unit))
  {
    result = Calendar.SECOND;
  }
  else if (MINUTES.equalsIgnoreCase(unit))
  {
    result = Calendar.MINUTE;
  }
  else if (HOURS.equalsIgnoreCase(unit))
  {
    result = Calendar.HOUR;
  }
  else if (DAYS.equalsIgnoreCase(unit))
  {
    result = Calendar.DATE;
  }
  else if (WEEKS.equalsIgnoreCase(unit))
  {
    result = Calendar.WEEK_OF_YEAR;
  }
  else if (MONTHS.equalsIgnoreCase(unit))
  {
    result = Calendar.MONTH;
  }
  else if (YEARS.equalsIgnoreCase(unit))
  {
    result = Calendar.YEAR;
  }
  return result;
}
 
Example 5
Source Project: das   File: TimeRangeShardLocator.java    License: Apache License 2.0 5 votes vote down vote up
private int upperEndpoint(Calendar cal) {
    if (field == Calendar.DAY_OF_MONTH  ||
        field == Calendar.DAY_OF_YEAR ||
        field == Calendar.WEEK_OF_YEAR ||
        field == Calendar.WEEK_OF_MONTH) {

        return cal.getActualMaximum(field);
    } else {
        return getMaxRange();
    }
}
 
Example 6
public static Calendar startOf(int field, long timeRef){
    Calendar result = Calendar.getInstance();
    result.setTimeInMillis(timeRef);
    result.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
    result.clear(Calendar.MINUTE);
    result.clear(Calendar.SECOND);
    result.clear(Calendar.MILLISECOND);
    switch(field){
        case Calendar.DAY_OF_MONTH:
        case Calendar.DAY_OF_WEEK:
        case Calendar.DAY_OF_WEEK_IN_MONTH:
        case Calendar.DAY_OF_YEAR:
            /* nothing to do, as HOUR_OF_DAY is already 0 */
            break;
        case Calendar.WEEK_OF_YEAR:
            result.set(Calendar.DAY_OF_WEEK, result.getFirstDayOfWeek());
            break;
        case Calendar.MONTH:
            result.set(Calendar.DAY_OF_MONTH, 1);
            break;
        case Calendar.YEAR:
            result.set(Calendar.DAY_OF_YEAR, 1);
            break;
        default:
            throw new RuntimeException("date field not supported: " + field);
    }
    return result;
}
 
Example 7
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
    super.onQueryComplete(token, cookie, cursor);
    if ((cursor != null) && cursor.moveToFirst()) {
        if (token == QUERY_CURRENT_ACTIVITY_STATS) {
            long avg = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryActivity.X_AVG_DURATION));
            viewModel.mAvgDuration.setValue(getResources().
                    getString(R.string.avg_duration_description, TimeSpanFormatter.format(avg)));

            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext());
            String formatString = sharedPref.getString(SettingsActivity.KEY_PREF_DATETIME_FORMAT,
                    getResources().getString(R.string.default_datetime_format));

            long start = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryActivity.X_START_OF_LAST));

            viewModel.mStartOfLast.setValue(getResources().
                    getString(R.string.last_done_description, DateFormat.format(formatString, start)));

        }else if(token == QUERY_CURRENT_ACTIVITY_TOTAL) {
            StatParam p = (StatParam)cookie;
            long total = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryStats.DURATION));

            String x = DateHelper.dateFormat(p.field).format(p.end);
            x = x + ": " + TimeSpanFormatter.format(total);
            switch(p.field){
                case Calendar.DAY_OF_YEAR:
                    viewModel.mTotalToday.setValue(x);
                    break;
                case Calendar.WEEK_OF_YEAR:
                    viewModel.mTotalWeek.setValue(x);
                    break;
                case Calendar.MONTH:
                    viewModel.mTotalMonth.setValue(x);
                    break;
            }
        }
    }
}
 
Example 8
Source Project: lams   File: DateBuilder.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static int translate(IntervalUnit unit) {
    switch(unit) {
        case DAY : return Calendar.DAY_OF_YEAR;
        case HOUR : return Calendar.HOUR_OF_DAY;
        case MINUTE : return Calendar.MINUTE;
        case MONTH : return Calendar.MONTH;
        case SECOND : return Calendar.SECOND;
        case MILLISECOND : return Calendar.MILLISECOND;
        case WEEK : return Calendar.WEEK_OF_YEAR;
        case YEAR : return Calendar.YEAR;
        default : throw new IllegalArgumentException("Unknown IntervalUnit");
    }
}
 
Example 9
private String getFieldAsString(final int field) {
    if (field == Calendar.YEAR) {
        if (unspecifiedFields.contains(Calendar.YEAR)) {
            return UNSPECIFIED_YEAR;
        } else {
            return String.format("%4d", c.get(field));
        }
    } else if (field == Calendar.MONTH) {
        if (unspecifiedFields.contains(Calendar.MONTH)) {
            return UNSPECIFIED_MONTH;
        } else {
            return String.format("%02d", c.get(field));
        }
    } else if (field >= Calendar.WEEK_OF_YEAR && field <= Calendar.DAY_OF_WEEK_IN_MONTH) {
        if (unspecifiedFields.contains(Calendar.DATE)) {
            return UNSPECIFIED_DATE;
        } else {
            return String.format("%02d", c.get(field));
        }
    } else if (field >= Calendar.HOUR && field <= Calendar.HOUR_OF_DAY) {
        if (unspecifiedFields.contains(Calendar.HOUR_OF_DAY)) {
            return UNSPECIFIED_HOUR;
        } else {
            return String.format("%02d", c.get(field));
        }
    } else if (field == Calendar.MINUTE) {
        if (unspecifiedFields.contains(Calendar.MINUTE)) {
            return UNSPECIFIED_MINUTE;
        } else {
            return String.format("%02d", c.get(field));
        }
    } else {
        return String.format("%s", c.get(field));
    }
}
 
Example 10
Source Project: development   File: TimeSlice.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Operation is based on java util calendar in order to support daylight
 * saving times.
 */
public TimeSlice previous() {
    long newStart = start;
    long newEnd = end;
    Calendar temp = Calendar.getInstance();
    temp.setTimeInMillis(start);
    int field = 0;
    switch (period) {
    case HOUR:
        field = Calendar.HOUR_OF_DAY;
        break;
    case DAY:
        field = Calendar.DAY_OF_MONTH;
        break;
    case WEEK:
        field = Calendar.WEEK_OF_YEAR;
        break;
    case MONTH:
        field = Calendar.MONTH;
        break;
    default:
        break;
    }
    temp.add(field, -1);
    newStart = temp.getTimeInMillis();
    temp.setTimeInMillis(end);
    temp.add(field, -1);
    newEnd = temp.getTimeInMillis();
    return new TimeSlice(newStart, newEnd, period);
}
 
Example 11
Source Project: constellation   File: DateAxis.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Makes dates even, in the sense of that years always begin in January,
 * months always begin on the 1st and days always at midnight.
 *
 * @param dates The list of dates.
 * @return The new list of dates.
 */
private List<Date> makeDatesEven(List<Date> dates, Calendar calendar) {
    // if the dates contain more dates than just the lower and upper bounds, make the dates in between even.
    if (dates.size() > 2) {
        List<Date> evenDates = new ArrayList<>();

        // for each interval, modify the date slightly by a few millis, to make sure they are different days.
        // this is because Axis stores each value and won't update the tick labels, if the value is already known.
        // this happens if you display days and then add a date many years in the future the tick label will still be displayed as day.
        for (int i = 0; i < dates.size(); i++) {
            calendar.setTime(dates.get(i));
            switch (actualInterval.interval) {
                case Calendar.YEAR:
                    // if it's not the first or last date (lower and upper bound), make the year begin with first month and let the months begin with first day.
                    if (i != 0 && i != dates.size() - 1) {
                        calendar.set(Calendar.MONTH, 0);
                        calendar.set(Calendar.DATE, 1);
                    }
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 6);
                    break;
                case Calendar.MONTH:
                    // if it's not the first or last date (lower and upper bound), make the months begin with first day.
                    if (i != 0 && i != dates.size() - 1) {
                        calendar.set(Calendar.DATE, 1);
                    }
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 5);
                    break;
                case Calendar.WEEK_OF_YEAR:
                    // make weeks begin with first day of week?
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 4);
                    break;
                case Calendar.DATE:
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 3);
                    break;
                case Calendar.HOUR:
                    if (i != 0 && i != dates.size() - 1) {
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                    }
                    calendar.set(Calendar.MILLISECOND, 2);
                    break;
                case Calendar.MINUTE:
                    if (i != 0 && i != dates.size() - 1) {
                        calendar.set(Calendar.SECOND, 0);
                    }
                    calendar.set(Calendar.MILLISECOND, 1);
                    break;
                case Calendar.SECOND:
                    calendar.set(Calendar.MILLISECOND, 0);
                    break;
                default:
                    break;
            }
            evenDates.add(calendar.getTime());
        }

        return evenDates;
    } else {
        return dates;
    }
}
 
Example 12
Source Project: nebula   File: DateHelper.java    License: Eclipse Public License 2.0 4 votes vote down vote up
public static int getCalendarTypeForString(String oneChar) {

		int calType = -1;

		switch (oneChar.charAt(0)) {
			case 'G':
				calType = Calendar.ERA;
				break;
			case 'y':
				calType = Calendar.YEAR;
				break;
			case 'M':
				calType = Calendar.MONTH;
				break;
			case 'd':
				calType = Calendar.DAY_OF_MONTH;
				break;
			case 'E':
				calType = Calendar.DAY_OF_WEEK;
				break;
			case 'D':
				calType = Calendar.DAY_OF_YEAR;
				break;
			case 'F':
				calType = Calendar.DATE;
				break;
			case 'h':
				calType = Calendar.HOUR;
				break;
			case 'm':
				calType = Calendar.MINUTE;
				break;
			case 's':
				calType = Calendar.SECOND;
				break;
			case 'S':
				calType = Calendar.MILLISECOND;
				break;
			case 'w':
				calType = Calendar.WEEK_OF_YEAR;
				break;
			case 'W':
				calType = Calendar.WEEK_OF_MONTH;
				break;
			case 'a':
				calType = Calendar.AM_PM;
				break;
			case 'k':
				calType = Calendar.HOUR_OF_DAY;
				break;
			case 'K':
				// ?
				break;
			case 'z':
				calType = Calendar.ZONE_OFFSET;
				break;
		}

		return calType;
	}
 
Example 13
Source Project: nebula   File: CDateTime.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Set the style of this CDateTime to work with dates and / or times as
 * determined by the given pattern. This will set the fields shown in the
 * text box and, if <code>DROP_DOWN</code> style is set, the fields of the
 * drop down component.<br>
 * This method is backed by an implementation of SimpleDateFormat, and as
 * such, any string pattern which is valid for SimpleDateFormat may be used.
 * Examples (US Locale):<br>
 * </code>setPattern("MM/dd/yyyy h:mm a");</code><br />
 * </code>setPattern("'Meeting @' h:mm a 'on' EEEE, MMM dd,
 * yyyy");</code><br />
 * 
 * @param pattern
 *            the pattern to use, if it is invalid, the original is restored
 * @throws IllegalArgumentException
 * @see SimpleDateFormat
 * @see #getPattern()
 * @see #setFormat(int)
 */
public void setPattern(String pattern) throws IllegalArgumentException {
	this.allowedTimezones = null;
	if (isOpen()) {
		setOpen(false);
	}
	df = new SimpleDateFormat(pattern, locale);
	df.setTimeZone(timezone);
	if (updateFields()) {
		this.pattern = pattern;
		this.format = -1;
		boolean wasDate = isDate;
		boolean wasTime = isTime;
		isDate = isTime = false;
		calendarFields = new int[field.length];
		for (int i = 0; i < calendarFields.length; i++) {
			calendarFields[i] = getCalendarField(field[i]);
			switch (calendarFields[i]) {
			case Calendar.AM_PM:
			case Calendar.HOUR:
			case Calendar.HOUR_OF_DAY:
			case Calendar.MILLISECOND:
			case Calendar.MINUTE:
			case Calendar.SECOND:
			case Calendar.ZONE_OFFSET:
				isTime = true;
				break;
			case Calendar.DAY_OF_MONTH:
			case Calendar.DAY_OF_WEEK:
			case Calendar.DAY_OF_WEEK_IN_MONTH:
			case Calendar.DAY_OF_YEAR:
			case Calendar.ERA:
			case Calendar.MONTH:
			case Calendar.WEEK_OF_MONTH:
			case Calendar.WEEK_OF_YEAR:
			case Calendar.YEAR:
				isDate = true;
				break;
			default:
				break;
			}
		}
		if (checkButton() && (isDate != wasDate || isTime != wasTime)) {
			if (defaultButtonImage) {
				if (isDate && isTime) {
					doSetButtonImage(Resources.getIconCalendarClock());
				} else if (isDate) {
					doSetButtonImage(Resources.getIconCalendar());
				} else {
					doSetButtonImage(Resources.getIconClock());
				}
			}
			updateNullText();
		}
		if (checkText()) {
			updateText();
		}
		if (isSimple()) {
			disposePicker();
			createPicker();
		}
	} else {
		throw new IllegalArgumentException(
				"Problem setting pattern: \"" + pattern + "\""); //$NON-NLS-1$ //$NON-NLS-2$
	}
}
 
Example 14
Source Project: dubbo-spring-boot-learning   File: DateUtils.java    License: MIT License 4 votes vote down vote up
/**
 * 获取日期绝对差
 *
 * @param d1    日期1
 * @param d2    日期2
 * @param field Calendar字段,YEAR、MONTH等
 * @return 日期差
 */
public static long diff(Date d1, Date d2, int field) {
    long ms = d2.getTime() - d1.getTime();
    //如果d2在d1前面
    if (getCalendar(d2).before(getCalendar(d1))) {
        //记录后一个日期
        Date d0 = d2;
        d2 = d1;
        d1 = d0;
    }
    long res = 0;
    switch (field) {
        case Calendar.YEAR:
            Calendar c = getCalendar(d2);
            //将年设置成相同的
            c.set(Calendar.YEAR, year(d1));
            //然后比较日期前后关系,如果d0在d1前面,年份-1
            res = year(d2) - year(d1) - (c.before(getCalendar(d1)) ? 1 : 0);
            break;

        case Calendar.MONTH:
            int years = year(d2) - year(d1);
            Calendar c1 = getCalendar(d2);
            //将年设置成相同的
            c1.set(Calendar.YEAR, year(d1));
            //然后比较日期前后关系,如果d0在d1前面,月份-1
            c1.set(Calendar.MONTH, month(d1) - 1);
            res = (month(d2) >= month(d1) ? (month(d2) - month(d1)) : (month(d2) + 12 - month(d1)) % 12) + years * 12 - (c1.before(getCalendar(d1)) ? 1 : 0);
            break;

        case Calendar.WEEK_OF_YEAR:
            res = ms / (7 * 24 * 60 * 60 * 1000);
            break;

        case Calendar.DATE:
            res = ms / (24 * 60 * 60 * 1000);
            break;

        case Calendar.HOUR:
            res = ms / (60 * 60 * 1000);
            break;

        case Calendar.MINUTE:
            res = ms / (60 * 1000);
            break;

        case Calendar.SECOND:
            res = ms / (1000);
            break;

        case Calendar.MILLISECOND:
            res = ms;
            break;

        default:
            break;
    }
    return res;
}
 
Example 15
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    currentDateTime = new Date().getTime();
    Bundle bnd = new Bundle();
    switch (position) {
        case 0: // all
            break;
        case 1: // last 7 days
            bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7));
            bnd.putLong("end", currentDateTime);
            break;
        case 2: // last 30 days
            bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7 * 30));
            bnd.putLong("end", currentDateTime);
            break;
        case 3: // Day
            currentOffset = 0;
            currentRange = Calendar.DAY_OF_YEAR;
            loadRange(currentRange, currentOffset);
            break;
        case 4: // week
            currentOffset = 0;
            currentRange = Calendar.WEEK_OF_YEAR;
            loadRange(currentRange, currentOffset);
            break;
        case 5: // month
            currentOffset = 0;
            currentRange = Calendar.MONTH;
            loadRange(currentRange, currentOffset);
            break;
        case 6: // year
            currentOffset = 0;
            currentRange = Calendar.YEAR;
            loadRange(currentRange, currentOffset);
            break;
        default:
    }
    if(position < 3){
        rangeTextView.setVisibility(View.INVISIBLE);
        rangeEarlierImageView.setVisibility(View.INVISIBLE);
        rangeLaterImageView.setVisibility(View.INVISIBLE);
    }else{
        rangeTextView.setVisibility(View.VISIBLE);
        rangeEarlierImageView.setVisibility(View.VISIBLE);
        rangeLaterImageView.setVisibility(View.VISIBLE);
    }
    if(position < 1) {
        getLoaderManager().restartLoader(LOADER_ID_TIME, bnd, this);
    }else if(position < 3){
        getLoaderManager().restartLoader(LOADER_ID_RANGE, bnd, this);
    }
}
 
Example 16
Source Project: phoebus   File: IndexNameHelper.java    License: Eclipse Public License 1.0 4 votes vote down vote up
private void setDateSpanStartAndEnd(Instant time)
{
    Calendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(time.toEpochMilli());
    calendar.setFirstDayOfWeek(Calendar.SUNDAY);

    Integer dateSpanField = -1;

    if (dateSpanUnit.equals(YEAR))
    {
        // Roll the year back to the beginning (midnight of the first of the year).
        dateSpanField = Calendar.YEAR;
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.WEEK_OF_MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
    }
    if (dateSpanUnit.equals(MONTH))
    {
        // Roll the month back to the beginning (midnight of the first of the month).
        dateSpanField = Calendar.MONTH;
        calendar.set(Calendar.WEEK_OF_MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
    }
    if (dateSpanUnit.equals(WEEK))
    {
        // Roll the week back to the beginning (midnight Sunday).
        dateSpanField = Calendar.WEEK_OF_YEAR;
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    }
    if (dateSpanUnit.equals(DAY))
        dateSpanField = Calendar.DATE;

    // Roll the day back to midnight
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    spanStart = calendar.toInstant();

    calendar.add(dateSpanField, dateSpanValue);

    spanEnd = calendar.toInstant();
}
 
Example 17
Source Project: evosql   File: DateTimeType.java    License: Apache License 2.0 4 votes vote down vote up
public int getPart(Session session, Object dateTime, int part) {

        int calendarPart;
        int increment = 0;
        int divisor   = 1;

        switch (part) {

            case Types.SQL_INTERVAL_YEAR :
                calendarPart = Calendar.YEAR;
                break;

            case Types.SQL_INTERVAL_MONTH :
                increment    = 1;
                calendarPart = Calendar.MONTH;
                break;

            case Types.SQL_INTERVAL_DAY :
            case DAY_OF_MONTH :
                calendarPart = Calendar.DAY_OF_MONTH;
                break;

            case Types.SQL_INTERVAL_HOUR :
                calendarPart = Calendar.HOUR_OF_DAY;
                break;

            case Types.SQL_INTERVAL_MINUTE :
                calendarPart = Calendar.MINUTE;
                break;

            case Types.SQL_INTERVAL_SECOND :
                calendarPart = Calendar.SECOND;
                break;

            case DAY_OF_WEEK :
                calendarPart = Calendar.DAY_OF_WEEK;
                break;

            case WEEK_OF_YEAR :
                calendarPart = Calendar.WEEK_OF_YEAR;
                break;

            case SECONDS_MIDNIGHT : {
                if (typeCode == Types.SQL_TIME
                        || typeCode == Types.SQL_TIME_WITH_TIME_ZONE) {}
                else {
                    try {
                        Type target = withTimeZone
                                      ? Type.SQL_TIME_WITH_TIME_ZONE
                                      : Type.SQL_TIME;

                        dateTime = target.castToType(session, dateTime, this);
                    } catch (HsqlException e) {}
                }

                return ((TimeData) dateTime).getSeconds();
            }
            case TIMEZONE_HOUR :
                if (typeCode == Types.SQL_TIMESTAMP_WITH_TIME_ZONE) {
                    return ((TimestampData) dateTime).getZone() / 3600;
                } else {
                    return ((TimeData) dateTime).getZone() / 3600;
                }
            case TIMEZONE_MINUTE :
                if (typeCode == Types.SQL_TIMESTAMP_WITH_TIME_ZONE) {
                    return ((TimestampData) dateTime).getZone() / 60 % 60;
                } else {
                    return ((TimeData) dateTime).getZone() / 60 % 60;
                }
            case QUARTER :
                increment    = 1;
                divisor      = 3;
                calendarPart = Calendar.MONTH;
                break;

            case DAY_OF_YEAR :
                calendarPart = Calendar.DAY_OF_YEAR;
                break;

            default :
                throw Error.runtimeError(ErrorCode.U_S0500,
                                         "DateTimeType - " + part);
        }

        long millis = getMillis(dateTime);

        return HsqlDateTime.getDateTimePart(millis, calendarPart) / divisor
               + increment;
    }
 
Example 18
/**
 * Get the end date by the start date and option. Note that both dates are is at start of the day (00:00).
 *
 * @param startDate
 * @param option
 * @return
 */
public static Date getDateRangeEndDate(Date startDate, String option) {
	int calendarAddType = 0;
	int under = option.indexOf('_');
	int endQuantity;
	String type;
	if (under != -1) {
		// format 6_weeks
		type = option.substring(under + 1);
		endQuantity = under;
	} else {
		// format , 6W
		type = "" + option.charAt(option.length() - 1);
		endQuantity = option.length() - 1;
	}
	switch (type) {
	case YEARS_LONG:
	case YEARS_SHORT:
		calendarAddType = Calendar.YEAR;
		break;

	case MONTHS_LONG:
	case MONTHS_SHORT:
		calendarAddType = Calendar.MONTH;
		break;

	case DAYS_LONG:
	case DAYS_SHORT:
		calendarAddType = Calendar.DAY_OF_YEAR;
		break;

	case WEEKS_LONG:
	case WEEKS_SHORT:
		calendarAddType = Calendar.WEEK_OF_YEAR;
		break;

	default:
		Assert.assertUnreachable("type of option not supported");
		break;
	}

	int quantity = Integer.parseInt(option.substring(0, endQuantity));
	Calendar c = Calendar.getInstance();
	c.setTime(startDate);
	c.add(calendarAddType, quantity);
	Date res = c.getTime();
	return res;
}
 
Example 19
Source Project: jdotxt   File: Task.java    License: GNU General Public License v3.0 4 votes vote down vote up
private void init(String rawText, Date defaultPrependedDate) {
	TextSplitter splitter = TextSplitter.getInstance();
	TextSplitter.SplitResult splitResult = splitter.split(rawText);
	this.priority = splitResult.priority;
	this.text = splitResult.text;
	this.prependedDate = splitResult.prependedDate;
	this.completed = splitResult.completed;
	this.completionDate = splitResult.completedDate;

	this.contexts = ContextParser.getInstance().parse(text);
	this.projects = ProjectParser.getInstance().parse(text);
	this.mailAddresses = MailAddressParser.getInstance().parse(text);
	this.links = LinkParser.getInstance().parse(text);
	this.phoneNumbers = PhoneNumberParser.getInstance().parse(text);
	this.deleted = Strings.isEmptyOrNull(text);
	this.hidden = HiddenParser.getInstance().parse(text);
	this.thresholdDate = ThresholdDateParser.getInstance().parseThresholdDate(rawText);
	this.dueDate = ThresholdDateParser.getInstance().parseDueDate(rawText);
	String[] parsedRec = RecParser.getInstance().parse(rawText);

	rec = parsedRec != null;
	if (rec) {
		isFromThreshold = !(parsedRec[0].isEmpty());
		amount = Integer.parseInt(parsedRec[1]);
		if ("d".equals(parsedRec[2])) {
			duration = Calendar.DAY_OF_YEAR;
		} else if ("w".equals(parsedRec[2])) {
			duration = Calendar.WEEK_OF_YEAR;
		} else if ("m".equals(parsedRec[2])) {
			duration = Calendar.MONTH;
		} else if ("y".equals(parsedRec[2])) {
			duration = Calendar.YEAR;
		}
	}

	if (defaultPrependedDate != null
			&& Strings.isEmptyOrNull(this.prependedDate)) {
		SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
		this.prependedDate = formatter.format(defaultPrependedDate);
	}

	if (!Strings.isEmptyOrNull(this.prependedDate)) {
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		try {
			Date d = sdf.parse(this.prependedDate);
			this.relativeAge = RelativeDate.getRelativeDate(d);
		} catch (ParseException e) {
			// e.printStackTrace();
		}
	}
}
 
Example 20
Source Project: yandex-money-sdk-java   File: Weeks.java    License: MIT License 4 votes vote down vote up
@Override
public int getField() {
    return Calendar.WEEK_OF_YEAR;
}