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

The following examples show how to use java.util.Calendar#setTime() . 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: DateUtil.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * 根据指定的日期计算年龄
 * 
 * @param dob
 * @return 年龄
 */
public static int age(Date dob) {
	Calendar from = Calendar.getInstance();
	Calendar to = Calendar.getInstance();
	from.setTime(dob);
	to.setTime(new Date());
	int birthYYYY = from.get(Calendar.YEAR);
	int curYYYY = to.get(Calendar.YEAR);

	int ageInYears = curYYYY - birthYYYY;

	if (ageInYears < 0)
		ageInYears = 0;

	return ageInYears;
}
 
Example 2
Source File: StructuredQueryBuilder.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
String formatValue(Object value, String type) {
  if ( value == null ) {
    return "null";
  }
  Class<?> valClass = value.getClass();
  if ( String.class.isAssignableFrom(valClass) ) {
    return (String) value;
  } else if ( type != null &&
    ( type.endsWith("date") || type.endsWith("dateTime") || type.endsWith("time") ) &&
    ( Date.class.isAssignableFrom(valClass) || Calendar.class.isAssignableFrom(valClass) ) )
  {
    if ( Date.class.isAssignableFrom(valClass) ) {
      Calendar cal = Calendar.getInstance();
      cal.setTime((Date) value);
      value = cal;
    }
    if ( type.endsWith("date") ) {
      return DatatypeConverter.printDate((Calendar) value);
    } else if ( type.endsWith("dateTime") ) {
      return DatatypeConverter.printDateTime((Calendar) value);
    } else if ( type.endsWith("time") ) {
      return DatatypeConverter.printTime((Calendar) value);
    }
  }
  return value.toString();
}
 
Example 3
Source File: ScriptAddedFunctions.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static Object isWorkingDay( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
  Object FunctionContext ) {
  if ( ArgList.length == 1 ) {
    try {
      if ( isNull( ArgList[0] ) ) {
        return null;
      } else if ( isUndefined( ArgList[0] ) ) {
        return undefinedValue;
      } else {
        java.util.Date dIn = (java.util.Date) ArgList[0];
        Calendar startDate = Calendar.getInstance();
        startDate.setTime( dIn );
        if ( startDate.get( Calendar.DAY_OF_WEEK ) != Calendar.SATURDAY
          && startDate.get( Calendar.DAY_OF_WEEK ) != Calendar.SUNDAY ) {
          return Boolean.TRUE;
        }
        return Boolean.FALSE;
      }
    } catch ( Exception e ) {
      return null;
    }
  } else {
    throw new RuntimeException( "The function call isWorkingDay requires 1 argument." );
  }
}
 
Example 4
Source File: ConfigurationFile.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Date subtractDays(final Date date, final int days) {
    final Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    final int doy = calendar.get(Calendar.DAY_OF_YEAR);
    calendar.set(Calendar.DAY_OF_YEAR, doy - days);
    return calendar.getTime();
}
 
Example 5
Source File: WorkcalDeployer.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void processHoliday(HolidayDTO holiday, YearDTO year) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(holiday.getStartDate());

    Date currentDate = holiday.getStartDate();

    while (!currentDate.after(holiday.getEndDate())) {
        this.processHolidayByDate(holiday, year, currentDate);
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        currentDate = calendar.getTime();
    }
}
 
Example 6
Source File: CompactCalendarController.java    From CompactCalendarView with MIT License 5 votes vote down vote up
private void setMonthOffset(Calendar calendarWithFirstDayOfMonth, Date currentDate, int scrollOffset, int monthOffset) {
    calendarWithFirstDayOfMonth.setTime(currentDate);
    calendarWithFirstDayOfMonth.add(Calendar.MONTH, scrollOffset + monthOffset);
    calendarWithFirstDayOfMonth.set(Calendar.HOUR_OF_DAY, 0);
    calendarWithFirstDayOfMonth.set(Calendar.MINUTE, 0);
    calendarWithFirstDayOfMonth.set(Calendar.SECOND, 0);
    calendarWithFirstDayOfMonth.set(Calendar.MILLISECOND, 0);
}
 
Example 7
Source File: TimeUtils.java    From StoryForest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 将给定日期的给定部分(如:年,月,日)改变一定数值
 * <p>
 * @param datePart 日期字段
 * @param delta 改变量
 * @param date 日期
 * @return 修改后的日期
 */
private static Date add(int datePart, int delta, Date date) {
    Calendar c = Calendar.getInstance();
    if (date != null) {
        c.setTime(date);
    }
    c.add(datePart, delta);
    return c.getTime();
}
 
Example 8
Source File: orderTest.java    From SmartCity-ParkingManagement with Apache License 2.0 5 votes vote down vote up
@Test
public void checkSetSlotId(){
	DatabaseManager dbm= Mockito.mock(DatabaseManager.class);
	Map<String, Object> keys = new HashMap<>();
	Map<String, Object> fields = new HashMap<>();
	Date startTime =new Date();
	Calendar cal = Calendar.getInstance(); // creates calendar
    cal.setTime(startTime); // sets calendar time/date
    cal.add(Calendar.HOUR_OF_DAY, 2);
	SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    String onlyDate = format1.format(cal.getTime()); 
	keys.put("id", "1");
	fields.put("price", 10.0);
	fields.put("hoursAmount", 3);
	fields.put("driverId", "3333334");
	fields.put("slotId", "123");
	fields.put("date", onlyDate);
	fields.put("hour", 2);
	fields.put("id","1");
	fields.put("actualHour","1");
	Mockito.when(dbm.getObjectFieldsByKey("Order", keys)).thenReturn(fields);
	try{
		new Order("1",dbm).setSlotId("122");;
		fields.put("slotId", "122");
		Mockito.verify(dbm,Mockito.times(1)).update("Order", keys, fields);
	}catch (ParseException e) {
		e.printStackTrace();
	}
}
 
Example 9
Source File: ValueDataUtil.java    From hop with Apache License 2.0 5 votes vote down vote up
public static Object weekOfYear( 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.WEEK_OF_YEAR ) );
}
 
Example 10
Source File: AttendanceDetailAnalyseService.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 判断当前日期是否为法定节假日
 * @param detail
 * @param attendanceWorkDayConfigList
 * @return
 */
private boolean isHoliday( AttendanceDetail detail, List<AttendanceWorkDayConfig> attendanceWorkDayConfigList, DateOperation dateOperation) {
	if( attendanceWorkDayConfigList != null ){
		Date configDate = null;
		for( AttendanceWorkDayConfig workDayConfig : attendanceWorkDayConfigList ){
			try {
				configDate = dateOperation.getDateFromString( workDayConfig.getConfigDate() );
			} catch (Exception e) {
				logger.warn( "系统转换"+workDayConfig.getConfigDate()+"格式为日期时发生异常!" );
				logger.error(e);
			}
			//进行日期对比
			Calendar calendar_record = Calendar.getInstance();
			Calendar calendar_config = Calendar.getInstance();
			calendar_record.setTime( detail.getRecordDate() );
			calendar_config.setTime( configDate );				
			if( calendar_record.get( Calendar.YEAR ) == calendar_config.get( Calendar.YEAR )
				&& calendar_record.get( Calendar.MONTH ) == calendar_config.get( Calendar.MONTH )
				&& calendar_record.get( Calendar.DATE ) == calendar_config.get( Calendar.DATE )
				&& "Holiday".equalsIgnoreCase( workDayConfig.getConfigType() )
			){
				return true;
			}
		}
	}	
	return false;
}
 
Example 11
Source File: Millisecond.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a millisecond.
 *
 * @param time  the date-time (<code>null</code> not permitted).
 * @param zone  the time zone (<code>null</code> not permitted).
 * @param locale  the locale (<code>null</code> not permitted).
 *
 * @since 1.0.13
 */
public Millisecond(Date time, TimeZone zone, Locale locale) {
    Calendar calendar = Calendar.getInstance(zone, locale);
    calendar.setTime(time);
    this.millisecond = calendar.get(Calendar.MILLISECOND);
    this.second = (byte) calendar.get(Calendar.SECOND);
    this.minute = (byte) calendar.get(Calendar.MINUTE);
    this.hour = (byte) calendar.get(Calendar.HOUR_OF_DAY);
    this.day = new Day(time, zone, locale);
    peg(calendar);
}
 
Example 12
Source File: DateUtil.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 获取传入日期的后一天
 * @param date
 * @return
 */
public static String getDateAfDay1(String date){
    Date d = DateUtil.getDate(date);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);

    calendar.add(Calendar.DAY_OF_MONTH,1);
    return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
}
 
Example 13
Source File: MiBandService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private long whenToRetryNextBgTimer() {
    final long bg_time;
    Calendar expireDate = Calendar.getInstance();
    expireDate.setTimeInMillis(System.currentTimeMillis() + BG_UPDATE_INTERVAL);
    isNightMode = false;
    if (MiBandEntry.isNightModeEnabled()) {
        int nightModeInterval = MiBandEntry.getNightModeInterval();
        if (nightModeInterval != MiBandEntry.NIGHT_MODE_INTERVAL_STEP) {
            Date curr = Calendar.getInstance().getTime();
            Date start = MiBandEntry.getNightModeStart();
            Date end = MiBandEntry.getNightModeEnd();
            Boolean result = isBetweenValidTime(start, end, curr);
            UserError.Log.d(TAG, "isBetweenValidTime: " + result);
            if (result) {
                Calendar calTimeCal = Calendar.getInstance();
                calTimeCal.setTimeInMillis(System.currentTimeMillis() + nightModeInterval * Constants.MINUTE_IN_MS);
                if (compareTime(end, calTimeCal.getTime()) >= 0) {
                    Calendar calEndCal = Calendar.getInstance();
                    calEndCal.setTime(end);
                    calTimeCal.set(Calendar.HOUR_OF_DAY, calEndCal.get(Calendar.HOUR_OF_DAY));
                    calTimeCal.set(Calendar.MINUTE, calEndCal.get(Calendar.MINUTE));
                }
                expireDate.setTimeInMillis(calTimeCal.getTimeInMillis());
                isNightMode = true;
            }
        }
    }
    bg_time = expireDate.getTimeInMillis() - JoH.tsl();
    return bg_time;
}
 
Example 14
Source File: StringUtil.java    From ShoppingCartActivity with Apache License 2.0 5 votes vote down vote up
/**
 * 日期(月份)相加减
 * 
 * @param current
 * @param count
 * @return
 */
public static String monthCalculate(String current, int count) {
	// 日期字符串转换为date类型
	Date currentDate = getDate(current, "yyyy-MM");

	// 获取Calendar对象
	Calendar mCalendar = Calendar.getInstance();
	// 设置日期为当前已经选择的时间
	mCalendar.setTime(currentDate);
	// 进行时间相加减操作
	mCalendar.add(Calendar.MONTH, count);
	String date = StringUtil.getDate(mCalendar.getTime(), "yyyy-MM");
	return date;
}
 
Example 15
Source File: DateTimeUtil.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定日期的 0点0分0秒
 *
 * @param d
 *            指定日期
 * @return 指定日期的0点0分0秒
 */
private static long get24HourMill(Date d) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTimeInMillis();
}
 
Example 16
Source File: DateUtils.java    From Roothub with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date getDateBefore(Date date, int day) {
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(date);
  calendar.add(Calendar.DAY_OF_MONTH, -day);
  return calendar.getTime();
}
 
Example 17
Source File: CalendarType.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public Object fromStringValue(String xml) throws HibernateException {
	Calendar result = new GregorianCalendar();
	result.setTime( ( (Date) Hibernate.TIMESTAMP.fromStringValue(xml) ) );
	return result;
}
 
Example 18
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 4 votes vote down vote up
public void deleteDay() {
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    // Set a start and end time for our data, using a start time of 1 day before this moment.
    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.DAY_OF_YEAR, -1);
    long startTime = cal.getTimeInMillis();
    long syncStart = startTime - (1000 * 60 * 60 * 24);
    SQLiteDatabase db = getDatabase();
    if (db != null && db.isOpen()) {
        cupboard().withDatabase(db).delete(Workout.class, "start >= ?", "" + syncStart);
    } else {
        Log.w(TAG, "Warning: db is null");
    }
    //closeDatabase();
    // https://developers.google.com/android/reference/com/google/android/gms/fitness/request/DataDeleteRequest
    //  Create a delete request object, providing a data type and a time interval
    DataDeleteRequest request = new DataDeleteRequest.Builder()
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
            .deleteAllData()
            .deleteAllSessions()
            .build();

    // Invoke the History API with the Google API client object and delete request, and then
    // specify a callback that will check the result.
    Fitness.HistoryApi.deleteData(mClient, request)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        Log.i(TAG, "Successfully deleted last day of data.");
                    } else {
                        // The deletion will fail if the requesting app tries to delete data
                        // that it did not insert.
                        Log.i(TAG, "Failed to delete workout");
                    }
                }
            });
    Context context = getApplicationContext();
    if(context != null) {
        UserPreferences.setLastSync(context, syncStart);
    }
    populateHistoricalData();
}
 
Example 19
Source File: DateOperation.java    From o2oa with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * 得到某日期加上或减去分钟后的日期,min为负数时减去
 * 
 * @param date
 * @param month
 * @return "yyyy-MM-dd HH:mi:ss"
 */
public  String getMinutesAdd(Date date, int min) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(date);
	calendar.add(Calendar.MINUTE, min);
	return format3.format(calendar.getTime());
}
 
Example 20
Source File: TestUtils.java    From super-csv-annotation with Apache License 2.0 3 votes vote down vote up
public static Date minusMillseconds(final Date date, final int millsecondsToSubstract) {
    
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    
    cal.add(Calendar.MILLISECOND, -millsecondsToSubstract);
    
    return cal.getTime();
    
}