Java Code Examples for java.util.Calendar#get()

The following examples show how to use java.util.Calendar#get() . 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 check out the related API usage on the sidebar.
Example 1
Source File: HerdDateUtils.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a calendar for the current day that does not have the time set.
 *
 * @return the current date.
 */
public static Calendar getCurrentCalendarNoTime()
{
    // Get the current year, month, and day before we clear out the fields.
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DATE);

    // Clear out ALL the fields of the calendar.  If any are not cleared, we run the risk of something being set that we don't want.
    calendar.clear();

    // Update the calendar with just the year, month, and day.
    calendar.set(year, month, day);

    // Return the updated calendar.
    return calendar;
}
 
Example 2
Source File: LocaleController.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
public static String formatDateForBan(long date) {
    try {
        date *= 1000;
        Calendar rightNow = Calendar.getInstance();
        int year = rightNow.get(Calendar.YEAR);
        rightNow.setTimeInMillis(date);
        int dateYear = rightNow.get(Calendar.YEAR);

        if (year == dateYear) {
            return getInstance().formatterBannedUntilThisYear.format(new Date(date));
        } else {
            return getInstance().formatterBannedUntil.format(new Date(date));
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
    return "LOC_ERR";
}
 
Example 3
Source File: TimeUtil.java    From FLogger with Apache License 2.0 6 votes vote down vote up
/**
 * 获取当前时间
 * @return 时分秒,格式如122415,12时24分15秒
 */
public static String getCurrTime() {
	StringBuffer sb = new StringBuffer(30);
	Calendar nowtime = Calendar.getInstance();
	int _hour = nowtime.get(Calendar.HOUR_OF_DAY); //获取小时
	int _minute = nowtime.get(Calendar.MINUTE); //获取分钟
	int _second = nowtime.get(Calendar.SECOND); //获取秒数
	if(_hour <10){
		sb.append("0");
	}
	sb.append(_hour);
	if(_minute <10){
		sb.append("0");
	}
	sb.append(_minute);
	if(_second <10){
		sb.append("0");
	}
	sb.append(_second);

	return sb.toString();		
}
 
Example 4
Source File: Lang_8_FastDatePrinter_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void appendTo(StringBuffer buffer, Calendar calendar) {
    TimeZone zone = calendar.getTimeZone();
    if (zone.useDaylightTime()
            && calendar.get(Calendar.DST_OFFSET) != 0) {
        buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale));
    } else {
        buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale));
    }
}
 
Example 5
Source File: WebRuleBaseValues.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This will ensure that the toDate is never larger than 2100, currently
 * doesn't do any throttling on the from date
 */
private void throttleDates() {
    if (getToDateValue() != null) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getToDateValue());
        if (calendar.get(Calendar.YEAR) > TO_DATE_UPPER_LIMIT) {
            calendar.set(Calendar.YEAR, TO_DATE_UPPER_LIMIT);
            setToDateValue(new Timestamp(calendar.getTimeInMillis()));
            setToDateString(new SimpleDateFormat("MM/dd/yyyy").format(getToDateValue()));
        }
    }
}
 
Example 6
Source File: OsLib.java    From XPrivacyLua with GNU General Public License v3.0 5 votes vote down vote up
private int timeZoneOffset(Calendar d) {
	int localStandarTimeMillis = ( 
			d.get(Calendar.HOUR_OF_DAY) * 3600 +
			d.get(Calendar.MINUTE) * 60 +
			d.get(Calendar.SECOND)) * 1000;
	return d.getTimeZone().getOffset(
			1,
			d.get(Calendar.YEAR),
			d.get(Calendar.MONTH),
			d.get(Calendar.DAY_OF_MONTH),
			d.get(Calendar.DAY_OF_WEEK), 
			localStandarTimeMillis) / 1000;
}
 
Example 7
Source File: PendingCalcs.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private static boolean isDifferentDayInPast(long now, long last, long period) {
    Calendar lastRestoreCalendar = Calendar.getInstance();
    lastRestoreCalendar.setTimeInMillis(last);

    return period == DateUtils.DAY_IN_MILLIS &&
            lastRestoreCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.getInstance().get(Calendar.DAY_OF_WEEK) &&
            now > last;
}
 
Example 8
Source File: UtilAll.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
public static boolean isItTimeToDo(final String when) {
    String[] whiles = when.split(";");
    if (whiles.length > 0) {
        Calendar now = Calendar.getInstance();
        for (String w : whiles) {
            int nowHour = Integer.parseInt(w);
            if (nowHour == now.get(Calendar.HOUR_OF_DAY)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 9
Source File: Arja_0025_s.java    From coming with MIT License 5 votes vote down vote up
static int reduceAndCorrect(Calendar start, Calendar end, int field, int difference) {
    end.add( field, -1 * difference );
    int endValue = end.get(field);
    int startValue = start.get(field);
    if (endValue < startValue) {
        int newdiff = startValue - endValue;
        end.add( field, newdiff );
        return newdiff;
    } else {
        return 0;
    }
}
 
Example 10
Source File: DateUtils.java    From jeewx-api with Apache License 2.0 5 votes vote down vote up
/**
 * 计算两个时间之间的差值,根据标志的不同而不同
 * 
 * @param flag
 *            计算标志,表示按照年/月/日/时/分/秒等计算
 * @param calSrc
 *            减数
 * @param calDes
 *            被减数
 * @return 两个日期之间的差值
 */
public static int dateDiff(char flag, Calendar calSrc, Calendar calDes) {

	long millisDiff = getMillis(calSrc) - getMillis(calDes);

	if (flag == 'y') {
		return (calSrc.get(calSrc.YEAR) - calDes.get(calDes.YEAR));
	}

	if (flag == 'd') {
		return (int) (millisDiff / DAY_IN_MILLIS);
	}

	if (flag == 'h') {
		return (int) (millisDiff / HOUR_IN_MILLIS);
	}

	if (flag == 'm') {
		return (int) (millisDiff / MINUTE_IN_MILLIS);
	}

	if (flag == 's') {
		return (int) (millisDiff / SECOND_IN_MILLIS);
	}

	return 0;
}
 
Example 11
Source File: ExsltDatetime.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parse the input string and return the corresponding calendar field
 * number.
 */
private static double getNumber(String in, String[] formats, int calField)
  throws ParseException
{
  Calendar cal = Calendar.getInstance();
  cal.setLenient(false);
  // Try the allowed formats, from longest to shortest.
  Date date = testFormats(in, formats);
  if (date == null) return Double.NaN;
  cal.setTime(date);
  return cal.get(calField);
}
 
Example 12
Source File: ValueDataUtil.java    From hop with Apache License 2.0 5 votes vote down vote up
public static Object secondOfMinute( IValueMeta metaA, Object dataA ) throws HopValueException {
  if ( dataA == null ) {
    return null;
  }

  Calendar calendar = Calendar.getInstance();
  calendar.setTime( metaA.getDate( dataA ) );
  return new Long( calendar.get( Calendar.SECOND ) );
}
 
Example 13
Source File: DateExtractYearMonthDayIntegerValues.java    From tutorials with MIT License 4 votes vote down vote up
int getYear(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    return calendar.get(Calendar.YEAR);
}
 
Example 14
Source File: CalendarUtils.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public static boolean isSameDay(final Calendar cal1, final Calendar cal2)
{
  return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
}
 
Example 15
Source File: Lang_21_DateUtils_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Calendar-version for fragment-calculation in any unit
 * 
 * @param calendar the calendar to work with, not null
 * @param fragment the Calendar field part of calendar to calculate 
 * @param unit Calendar field defining the unit
 * @return number of units within the fragment of the calendar
 * @throws IllegalArgumentException if the date is <code>null</code> or 
 * fragment is not supported
 * @since 2.4
 */
private static long getFragment(Calendar calendar, int fragment, int unit) {
    if(calendar == null) {
        throw  new IllegalArgumentException("The date must not be null"); 
    }
    long millisPerUnit = getMillisPerUnit(unit);
    long result = 0;
    
    // Fragments bigger than a day require a breakdown to days
    switch (fragment) {
        case Calendar.YEAR:
            result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
            break;
        case Calendar.MONTH:
            result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
            break;
    }

    switch (fragment) {
        // Number of days already calculated for these cases
        case Calendar.YEAR:
        case Calendar.MONTH:
        
        // The rest of the valid cases
        case Calendar.DAY_OF_YEAR:
        case Calendar.DATE:
            result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.HOUR_OF_DAY:
            result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.MINUTE:
            result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.SECOND:
            result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
            break;
        case Calendar.MILLISECOND: break;//never useful
            default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
    }
    return result;
}
 
Example 16
Source File: SegmentedTimelineTest.java    From SIMVA-SoS with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up the fixture, for example, open a network connection.
 * This method is called before a test is executed.
 *
 * @throws Exception if there is a problem.
 */
@Before
public void setUp() throws Exception {
    // setup our test timelines
    //
    // Legend for comments below:
    // <spaces> = Segments included in the final timeline
    // EE       = Excluded segments via timeline rules
    // xx       = Exception segments inherited from base timeline exclusions

    // 1-ms test timeline using 5 included and 2 excluded segments.
    //
    // timeline start time = 0
    //   |
    //   v
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 ..
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+..
    // |  |  |  |  |  |EE|EE|  |  |  |  |  |EE|EE|  |  |  |  |  |  |EE|EE|    <-- msTimeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+..
    //  \_________  ________/            \_/
    //            \/                      |
    //       segment group         segment size = 1 ms
    //
    this.msTimeline = new SegmentedTimeline(1, 5, 2);
    this.msTimeline.setStartTime(0);

    // 4-ms test base timeline for ms2Timeline using 1 included and 1
    // excluded segments
    //
    // timeline start time = 0
    //   |
    //   v
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 ...
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |  |  |  |  |EE|EE|EE|EE|  |  |  |  |EE|EE|EE|EE|  |  |  |  |    <-- ms2BaseTimeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    //  \__________  _________/            \____  _____/
    //             \/                           \/
    //        segment group              segment size = 4 ms
    //
    this.ms2BaseTimeline = new SegmentedTimeline(4, 1, 1);
    this.ms2BaseTimeline.setStartTime(0);

    // 1-ms test timeline (with a baseTimeline) using 2 included and 2
    // excluded segments centered inside each base segment
    //
    // The ms2Timeline without a base would look like this:
    //
    //    timeline start time = 1
    //      |
    //      v
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 ...
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |EE|  |  |EE|EE|  |  |EE|EE|  |  |EE|EE|  |  |EE|EE|  |  |EE|    <-- ms2Timeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    //    \____  _____/            \_/
    //         \/                   |
    //    segment group      segment size = 1 ms
    //
    // With the base timeline some originally included segments are now
    // removed (see "xx" below):
    //
    //   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 ...
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |EE|  |  |EE|EE|xx|xx|EE|EE|  |  |EE|EE|xx|xx|EE|EE|  |  |EE|    <-- ms2Timeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    // |  |  |  |  |EE|EE|EE|EE|  |  |  |  |EE|EE|EE|EE|  |  |  |  |    <-- ms2BaseTimeline
    // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+...
    //
    this.ms2Timeline = new SegmentedTimeline(1, 2, 2);
    this.ms2Timeline.setStartTime(1);
    this.ms2Timeline.setBaseTimeline(this.ms2BaseTimeline);

    // test monday though friday timeline
    this.mondayFridayTimeline
            = SegmentedTimeline.newMondayThroughFridayTimeline();

    // test 9am-4pm Monday through Friday timeline
    this.fifteenMinTimeline
            = SegmentedTimeline.newFifteenMinuteTimeline();

    // find first Monday after 2001-01-01
    Calendar cal = new GregorianCalendar(
            SegmentedTimeline.NO_DST_TIME_ZONE);
    cal.set(2001, 0, 1, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        cal.add(Calendar.DATE, 1);
    }
    this.monday = (Calendar) cal.clone();

    // calculate 9am on the first Monday after 2001-01-01
    cal.add(Calendar.HOUR, 9);
    this.monday9am = (Calendar) cal.clone();
}
 
Example 17
Source File: ExsltDatetime.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
  * See above.
  */
 public static double dayOfWeekInMonth()
 {
    Calendar cal = Calendar.getInstance();
   return cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
}
 
Example 18
Source File: AvroWriteSupportInt96Avro17.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void writeValue(Type type, Schema avroSchema, Object value) {
  Schema nonNullAvroSchema = AvroSchemaConverter.getNonNull(avroSchema);
  Schema.Type avroType = nonNullAvroSchema.getType();
  if (avroType.equals(Schema.Type.BOOLEAN)) {
    recordConsumer.addBoolean((Boolean) value);
  } else if (avroType.equals(Schema.Type.INT)) {
    if (value instanceof Character) {
      recordConsumer.addInteger((Character) value);
    } else {
      recordConsumer.addInteger(((Number) value).intValue());
    }
  } else if (avroType.equals(Schema.Type.LONG)) {
    if (type.asPrimitiveType().getPrimitiveTypeName().equals(PrimitiveType.PrimitiveTypeName.INT96)) {
      final long NANOS_PER_HOUR = TimeUnit.HOURS.toNanos(1);
      final long NANOS_PER_MINUTE = TimeUnit.MINUTES.toNanos(1);
      final long NANOS_PER_SECOND = TimeUnit.SECONDS.toNanos(1);

      long timestamp = ((Number) value).longValue();
      Calendar calendar;
      if (timeZoneId != null && ! timeZoneId.isEmpty()) {
        calendar = Calendar.getInstance(TimeZone.getTimeZone(timeZoneId));
      } else {
        calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
      }
      calendar.setTime(new Date(timestamp));

      // Calculate Julian days and nanoseconds in the day
      LocalDate dt = LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH));
      int julianDays = (int) JulianFields.JULIAN_DAY.getFrom(dt);
      long nanos = (calendar.get(Calendar.HOUR_OF_DAY) * NANOS_PER_HOUR)
          + (calendar.get(Calendar.MINUTE) * NANOS_PER_MINUTE)
          + (calendar.get(Calendar.SECOND) * NANOS_PER_SECOND);

      // Write INT96 timestamp
      byte[] timestampBuffer = new byte[12];
      ByteBuffer buf = ByteBuffer.wrap(timestampBuffer);
      buf.order(ByteOrder.LITTLE_ENDIAN).putLong(nanos).putInt(julianDays);

      // This is the properly encoded INT96 timestamp
      Binary timestampBinary = Binary.fromReusedByteArray(timestampBuffer);
      recordConsumer.addBinary(timestampBinary);
    } else {
      recordConsumer.addLong(((Number) value).longValue());
    }
  } else if (avroType.equals(Schema.Type.FLOAT)) {
    recordConsumer.addFloat(((Number) value).floatValue());
  } else if (avroType.equals(Schema.Type.DOUBLE)) {
    recordConsumer.addDouble(((Number) value).doubleValue());
  } else if (avroType.equals(Schema.Type.BYTES)) {
    if (value instanceof byte[]) {
      recordConsumer.addBinary(Binary.fromReusedByteArray((byte[]) value));
    } else {
      recordConsumer.addBinary(Binary.fromReusedByteBuffer((ByteBuffer) value));
    }
  } else if (avroType.equals(Schema.Type.STRING)) {
    recordConsumer.addBinary(fromAvroString(value));
  } else if (avroType.equals(Schema.Type.RECORD)) {
    writeRecord(type.asGroupType(), nonNullAvroSchema, value);
  } else if (avroType.equals(Schema.Type.ENUM)) {
    recordConsumer.addBinary(Binary.fromString(value.toString()));
  } else if (avroType.equals(Schema.Type.ARRAY)) {
    listWriter.writeList(type.asGroupType(), nonNullAvroSchema, value);
  } else if (avroType.equals(Schema.Type.MAP)) {
    writeMap(type.asGroupType(), nonNullAvroSchema, (Map<CharSequence, ?>) value);
  } else if (avroType.equals(Schema.Type.UNION)) {
    writeUnion(type.asGroupType(), nonNullAvroSchema, value);
  } else if (avroType.equals(Schema.Type.FIXED)) {
    recordConsumer.addBinary(Binary.fromReusedByteArray(((GenericFixed) value).bytes()));
  }
}
 
Example 19
Source File: FlexibleCalendarView.java    From FlexibleCalendar with MIT License 3 votes vote down vote up
private SelectedDateItem computeNewSelectedDateItem(int difference) {

            Calendar cal = Calendar.getInstance();
            cal.set(displayYear, displayMonth, 1);
            cal.add(Calendar.MONTH, -difference);

            return new SelectedDateItem(cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH), 1);

        }
 
Example 20
Source File: MonthDay.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Constructs a MonthDay from a <code>java.util.Calendar</code>
 * using exactly the same field values avoiding any time zone effects.
 * <p>
 * Each field is queried from the Calendar and assigned to the MonthDay.
 * <p>
 * This factory method ignores the type of the calendar and always
 * creates a MonthDay with ISO chronology. It is expected that you
 * will only pass in instances of <code>GregorianCalendar</code> however
 * this is not validated.
 *
 * @param calendar  the Calendar to extract fields from
 * @return the created MonthDay, never null
 * @throws IllegalArgumentException if the calendar is null
 * @throws IllegalArgumentException if the monthOfYear or dayOfMonth is invalid for the ISO chronology
 */
public static MonthDay fromCalendarFields(Calendar calendar) {
    if (calendar == null) {
        throw new IllegalArgumentException("The calendar must not be null");
    }
    return new MonthDay(calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
}