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

The following examples show how to use java.util.Calendar#set() . 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: ICalDate.java    From biweekly with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Creates a new date-time value.
 * @param date the date-time value
 * @param rawComponents the raw date-time value as parsed from the input
 * stream
 * @param hasTime true if the date-time value has a time component, false if
 * not
 */
public ICalDate(Date date, DateTimeComponents rawComponents, boolean hasTime) {
	if (!hasTime) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		date = c.getTime();
	}

	setTime(date.getTime());
	this.rawComponents = rawComponents;
	this.hasTime = hasTime;
}
 
Example 2
Source File: PersianRadialPickerLayout.java    From PersianDateRangePicker with Apache License 2.0 6 votes vote down vote up
/**
 * Announce the currently-selected time when launched.
 */
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
  if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
    // Clear the event's current text so that only the current time will be spoken.
    event.getText().clear();
    Calendar time = Calendar.getInstance();
    time.set(Calendar.HOUR, getHours());
    time.set(Calendar.MINUTE, getMinutes());
    long millis = time.getTimeInMillis();
    int flags = DateUtils.FORMAT_SHOW_TIME;
    if (mIs24HourMode) {
      flags |= DateUtils.FORMAT_24HOUR;
    }
    String timeString = LanguageUtils.getPersianNumbers(
      DateUtils.formatDateTime(getContext(), millis, flags)); //TODO: Changed Here.
    event.getText().add(timeString);
    return true;
  }
  return super.dispatchPopulateAccessibilityEvent(event);
}
 
Example 3
Source File: PurapServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see org.kuali.kfs.module.purap.document.service.PurapService#isDateMoreThanANumberOfDaysAway(java.sql.Date, int)
 */
@Override
public boolean isDateMoreThanANumberOfDaysAway(Date compareDate, int daysAway) {
    LOG.debug("isDateMoreThanANumberOfDaysAway() started");

    Date todayAtMidnight = dateTimeService.getCurrentSqlDateMidnight();
    Calendar daysAwayCalendar = dateTimeService.getCalendar(todayAtMidnight);
    daysAwayCalendar.add(Calendar.DATE, daysAway);
    Timestamp daysAwayTime = new Timestamp(daysAwayCalendar.getTime().getTime());
    Calendar compareCalendar = dateTimeService.getCalendar(compareDate);
    compareCalendar.set(Calendar.HOUR, 0);
    compareCalendar.set(Calendar.MINUTE, 0);
    compareCalendar.set(Calendar.SECOND, 0);
    compareCalendar.set(Calendar.MILLISECOND, 0);
    compareCalendar.set(Calendar.AM_PM, Calendar.AM);
    Timestamp compareTime = new Timestamp(compareCalendar.getTime().getTime());
    return (compareTime.compareTo(daysAwayTime) > 0);
}
 
Example 4
Source File: LetvUtils.java    From letv with Apache License 2.0 6 votes vote down vote up
public static int getMinusDaysBetweenTwoDate(long endTime, long startTime) {
    Date endDate = new Date(endTime);
    Date beginDate = new Date(startTime);
    Calendar c = Calendar.getInstance();
    c.setTime(endDate);
    c.set(11, 0);
    c.set(12, 0);
    c.set(13, 0);
    c.set(14, 0);
    long endMilliSec = c.getTimeInMillis();
    c.setTime(beginDate);
    c.set(11, 0);
    c.set(12, 0);
    c.set(13, 0);
    c.set(14, 0);
    return (int) ((endMilliSec - c.getTimeInMillis()) / 86400000);
}
 
Example 5
Source File: DateToLocalDateTimeConverterUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() {
    // given
    Calendar calendar = Calendar.getInstance();
    calendar.set(2010, 10, 10, 8, 20);
    Date dateToConvert = calendar.getTime();

    // when
    LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);

    // then
    assertEquals(2010, localDateTime.get(ChronoField.YEAR));
    assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
    assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
    assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
    assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
 
Example 6
Source File: HistoricTaskInstanceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testHistoricTaskInstanceQueryByTaskDefinitionKeys() throws Exception {
    Calendar start = Calendar.getInstance();
    start.set(Calendar.MILLISECOND, 0);
    processEngineConfiguration.getClock().setCurrentTime(start.getTime());

    // First instance is finished
    ProcessInstance finishedInstance = runtimeService.startProcessInstanceByKey("taskDefinitionKeysProcess", "myBusinessKey");
    processEngineConfiguration.getClock().reset();

    List<Task> tasks = taskService.createTaskQuery().processInstanceId(finishedInstance.getId()).list();
    for (Task task : tasks) {
        taskService.complete(task.getId());
    }

    waitForHistoryJobExecutorToProcessAllJobs(7000, 100);

    assertThat(historyService.createHistoricTaskInstanceQuery().taskDefinitionKeys(Arrays.asList("taskKey1", "taskKey123", "invalid")).list())
        .extracting(TaskInfo::getTaskDefinitionKey, TaskInfo::getName)
        .containsExactlyInAnyOrder(
            tuple("taskKey1", "Task A"),
            tuple("taskKey123", "Task B")
        );
    assertThat(historyService.createHistoricTaskInstanceQuery().taskDefinitionKeys(Arrays.asList("taskKey1", "taskKey123", "invalid")).count())
        .isEqualTo(2L);

    assertThat(historyService.createHistoricTaskInstanceQuery().taskDefinitionKeys(Arrays.asList("invalid1", "invalid2")).list()).isEmpty();
    assertThat(historyService.createHistoricTaskInstanceQuery().taskDefinitionKeys(Arrays.asList("invalid1", "invalid2")).count()).isEqualTo(0L);

    assertThat(historyService.createHistoricTaskInstanceQuery().or().taskId("invalid").taskDefinitionKeys(Arrays.asList("taskKey1", "taskKey123", "invalid"))
        .endOr().list())
        .extracting(TaskInfo::getTaskDefinitionKey, TaskInfo::getName)
        .containsExactlyInAnyOrder(
            tuple("taskKey1", "Task A"),
            tuple("taskKey123", "Task B")
        );
    assertThat(historyService.createHistoricTaskInstanceQuery().or().taskId("invalid").taskDefinitionKeys(Arrays.asList("taskKey1", "taskKey123", "invalid"))
        .endOr().count()).isEqualTo(2L);
}
 
Example 7
Source File: Utils.java    From hipda with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isInTimeRange(String begin, String end) {
    try {
        //format hh:mm
        String[] bPieces = begin.split(":");
        int bHour = Integer.parseInt(bPieces[0]);
        int bMinute = Integer.parseInt(bPieces[1]);

        String[] ePieces = end.split(":");
        int eHour = Integer.parseInt(ePieces[0]);
        int eMinute = Integer.parseInt(ePieces[1]);


        Calendar now = Calendar.getInstance();
        Calendar beginCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();

        beginCal.set(Calendar.HOUR_OF_DAY, bHour);
        beginCal.set(Calendar.MINUTE, bMinute);
        beginCal.set(Calendar.SECOND, 0);
        beginCal.set(Calendar.MILLISECOND, 0);

        endCal.set(Calendar.HOUR_OF_DAY, eHour);
        endCal.set(Calendar.MINUTE, eMinute);
        endCal.set(Calendar.SECOND, 59);
        endCal.set(Calendar.MILLISECOND, 999);

        if (endCal.before(beginCal)) {
            endCal.add(Calendar.DATE, 1);
        }
        if (beginCal.after(now)) {
            beginCal.add(Calendar.DATE, -1);
            endCal.add(Calendar.DATE, -1);
        }

        return now.getTimeInMillis() >= beginCal.getTimeInMillis() && now.getTimeInMillis() <= endCal.getTimeInMillis();
    } catch (Exception e) {
        Logger.e(e);
        return false;
    }
}
 
Example 8
Source File: SecondTests.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Some checks for the getEnd() method.
 */
public void testGetEnd() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.ITALY);
    Calendar cal = Calendar.getInstance(Locale.ITALY);
    cal.set(2006, Calendar.JANUARY, 16, 3, 47, 55);
    cal.set(Calendar.MILLISECOND, 999);
    Second s = new Second(55, 47, 3, 16, 1, 2006);
    assertEquals(cal.getTime(), s.getEnd());
    Locale.setDefault(saved);
}
 
Example 9
Source File: SaveTaskBackend.java    From unitime with Apache License 2.0 5 votes vote down vote up
public static Date getScheduleDate(Session session, int date, int slot) {
	Calendar c = Calendar.getInstance(Locale.US);
	c.setTime(session.getSessionBeginDateTime());
	c.set(Calendar.HOUR, 0);
	c.set(Calendar.MINUTE, 0);
	c.set(Calendar.SECOND, 0);
	c.set(Calendar.MILLISECOND, 0);
	c.add(Calendar.DAY_OF_YEAR, date);
	c.add(Calendar.MINUTE, slot * 5);
	return c.getTime();
}
 
Example 10
Source File: DateConvertUtil.java    From spring-boot-demo-all with Apache License 2.0 5 votes vote down vote up
/**
 * 获得去年同期
 *
 * @param String date
 */
public static String getLastYearPeriod(String date) {
    Calendar ca = Calendar.getInstance();
    ca.setTime(StringToDate(date, "yyyy-MM-dd"));
    ca.add(Calendar.MONTH, -12);
    if (isMonthEnd(date)) {
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
    }
    return parseDateToString(ca.getTime(), "yyyy-MM-dd");
}
 
Example 11
Source File: DataFormatter.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
/**
 * Used internally to determine the maximum amount of space required by
 * a specific date/time/datetime format.
 * @param format The format to test.
 * @return The maximum width.
 */
private int getMaxDateWidth(String format) {
    
    Calendar cal = Calendar.getInstance();
    int maxWidth = 0;
    
    
    /*
     * The following will attempt to cover all of the months in the year
     * (on the assumption the current formatter includes the month name)
     * as well as all of the days of the week and double-digit day of month
     * numbers.
     */
    for (int month = 1; month <= 12; month++) {
        
        for (int dayOfMonth = 20; dayOfMonth < 28; dayOfMonth++) {
            
            cal.set(2007, month, dayOfMonth, 23, 59, 59);
            
            int width = formatDate(format, cal.getTime()).length();
            if (width > maxWidth) {
                
                maxWidth = width;
            }
        }
    }
    
    return maxWidth;
}
 
Example 12
Source File: FixedDateFormat.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private long calcMidnightMillis(final long time, final int addDays) {
    final Calendar cal = Calendar.getInstance(timeZone);
    cal.setTimeInMillis(time);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    cal.add(Calendar.DATE, addDays);
    return cal.getTimeInMillis();
}
 
Example 13
Source File: TransactionSellBuyFragment.java    From bitshares_wallet with MIT License 5 votes vote down vote up
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.okButton:
            ConfirmOrderDialog.ConfirmOrderData confirmOrderData = new ConfirmOrderDialog.ConfirmOrderData();
            if (transactionType == TRANSACTION_BUY) {
                confirmOrderData.setOperationName(getResources().getString(R.string.title_buy));
            } else {
                confirmOrderData.setOperationName(getResources().getString(R.string.title_sell));
            }
            confirmOrderData.setPrice(pEditText.getText().toString());
            confirmOrderData.setQuantity(qEditText.getText().toString());
            confirmOrderData.setTotal(tEditText.getText().toString());
            confirmOrderData.setFree(fEditText.getText().toString());
            confirmOrderData.setQuantityType(utils.getAssetSymbolDisply(quoteAsset));
            confirmOrderData.setTotalType(utils.getAssetSymbolDisply(baseAsset));

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 5);
            calendar.getTime();
            SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            confirmOrderData.setTimeExpiration(formatter.format(calendar.getTimeInMillis()));
            ConfirmOrderDialog confirmOrderDialog = new ConfirmOrderDialog(getActivity(), confirmOrderData);
            confirmOrderDialog.setListener(this);
            confirmOrderDialog.show();
            break;
        case R.id.restButton:
            resetInputInfo();
            break;
    }
}
 
Example 14
Source File: JapaneseDate.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int lengthOfYear() {
    Calendar jcal = Calendar.getInstance(JapaneseChronology.LOCALE);
    jcal.set(Calendar.ERA, era.getValue() + JapaneseEra.ERA_OFFSET);
    jcal.set(yearOfEra, isoDate.getMonthValue() - 1, isoDate.getDayOfMonth());
    return  jcal.getActualMaximum(Calendar.DAY_OF_YEAR);
}
 
Example 15
Source File: XmlHandlerUnitTest.java    From hop with Apache License 2.0 5 votes vote down vote up
@Test
public void addTagValueDate() {
  String result = "2014/12/29 15:59:45.789";
  Calendar aDate = new GregorianCalendar();
  aDate.set( 2014, ( 12 - 1 ), 29, 15, 59, 45 );
  aDate.set( Calendar.MILLISECOND, 789 );

  assertEquals( "<adate>" + result + "</adate>" + cr, XmlHandler.addTagValue( "adate", aDate.getTime() ) );
  assertEquals( "<adate>" + result + "</adate>" + cr, XmlHandler.addTagValue( "adate", aDate.getTime(), true ) );
  assertEquals( "<adate>" + result + "</adate>", XmlHandler.addTagValue( "adate", aDate.getTime(), false ) );
}
 
Example 16
Source File: DateUtil.java    From seckill-rocketmq with Apache License 2.0 5 votes vote down vote up
/**
 * 获取本月最后一天的23:59:59
 * @return
 */
public static Date getCurrMonthEndDate() {
    // 查询结束时间--本月最后一秒
    Calendar lastDay = Calendar.getInstance();
    lastDay.set(Calendar.DAY_OF_MONTH, lastDay.getActualMaximum(Calendar.DAY_OF_MONTH));
    String last = DateUtil.formatDateYyyyMMdd2(lastDay.getTime());
    last = last + " 23:59:59";
    Date queryEndDate = DateUtil.parseNormalDateFromStr(last);
    return queryEndDate;
}
 
Example 17
Source File: DateUtilities.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Calendar removeMilliseconds(Calendar calendar) {
	Calendar returnCalendar = (Calendar) calendar.clone();
	returnCalendar.set(Calendar.MILLISECOND, 0);
	return returnCalendar;
}
 
Example 18
Source File: TestDateUtils.java    From joda-time-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testFormatDateRange() {
    Calendar startPartialCal = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
    startPartialCal.set(1985, 10, 27, 0, 0, 0);
    long startPartialMs = startPartialCal.getTimeInMillis();

    Calendar endPartialCal = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
    endPartialCal.set(1985, 11, 25, 0, 0, 0);
    long endPartialMs = endPartialCal.getTimeInMillis() + 1000; // Include buffer for formatDateRange() bug

    LocalDate startLocalDate = new LocalDate(1985, 11, 27);
    LocalDate endLocalDate = new LocalDate(1985, 12, 25);

    Calendar startCal = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
    startCal.set(1985, 10, 27, 5, 23, 5);
    long startMillis = startCal.getTimeInMillis();

    Calendar endCal = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
    endCal.set(1985, 11, 25, 20, 14, 25);
    long endMillis = endCal.getTimeInMillis();

    DateTime startDateTime = new DateTime(1985, 11, 27, 5, 23, 5, DateTimeZone.forID("America/Chicago"));
    DateTime endDateTime = new DateTime(1985, 12, 25, 20, 14, 25, DateTimeZone.forID("America/Chicago"));

    Context ctx = InstrumentationRegistry.getInstrumentation().getContext();

    for (int a = 0; a < FORMAT_DATE_RANGE_FLAGS.length; a++) {
        int flags = FORMAT_DATE_RANGE_FLAGS[a];

        // Start partial, end partial
        assertEquals(android.text.format.DateUtils.formatDateRange(ctx, startPartialMs, endPartialMs, flags),
            DateUtils.formatDateRange(ctx, startLocalDate, endLocalDate, flags));

        // Start instant, end instant
        assertEquals(android.text.format.DateUtils.formatDateRange(ctx, startMillis, endMillis, flags),
            DateUtils.formatDateRange(ctx, startDateTime, endDateTime, flags));

        // Same start/end time
        assertEquals(android.text.format.DateUtils.formatDateRange(ctx, startPartialMs, startPartialMs, flags),
            DateUtils.formatDateRange(ctx, startLocalDate, startLocalDate, flags));
        assertEquals(android.text.format.DateUtils.formatDateRange(ctx, startMillis, startMillis, flags),
            DateUtils.formatDateRange(ctx, startDateTime, startDateTime, flags));
    }
}
 
Example 19
Source File: DateUtils.java    From litchi with Apache License 2.0 3 votes vote down vote up
/**
 * 获取今天指定时间的Date
 * 
 * @param hour
 * @param minute
 * @param seconds
 * @param millSenconds
 * @return
 */
public static Calendar getSpecialTimeOfToday(int hour, int minute, int seconds, int millSenconds) {
	Calendar cal = getCalendar();
	cal.set(Calendar.HOUR_OF_DAY, hour);
	cal.set(Calendar.MINUTE, minute);
	cal.set(Calendar.SECOND, seconds);
	cal.set(Calendar.MILLISECOND, millSenconds);
	return cal;
}
 
Example 20
Source File: DateUtil.java    From AthenaServing with Apache License 2.0 2 votes vote down vote up
/**
 * 获取月份的天数
 *
 * @param year
 * @param month
 * @return
 */
public static int getDaysOfMonth(int year, int month) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month - 1, 1);
    return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}