Java Code Examples for java.util.Calendar.add()

The following are Jave code examples for showing how to use add() of the java.util.Calendar class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GongXianSheng   File: TimeUtils.java   View Source Code Vote up 6 votes
public static String getWeekStr(int numDay) {
	String weekStr = "";
	Date date = new Date();
	Calendar calendar = new GregorianCalendar();
	calendar.setTime(date);
	calendar.add(Calendar.DATE, numDay);//把日期往后增加一天.整数往后推,负数往前移动
	int mWay = calendar.get(Calendar.DAY_OF_WEEK);
	if (1 == mWay) {
		weekStr = "周日";
	} else if (2 == mWay) {
		weekStr = "周一";
	} else if (3 == mWay) {
		weekStr = "周二";
	} else if (4 == mWay) {
		weekStr = "周三";
	} else if (5 == mWay) {
		weekStr = "周四";
	} else if (6 == mWay) {
		weekStr = "周五";
	} else if (7 == mWay) {
		weekStr = "周六";
	}
	return weekStr;

}
 
Example 2
Project: Java-9-Concurrency-Cookbook-Second-Edition   File: PersonGenerator.java   View Source Code Vote up 6 votes
public static List<Person> generatePersonList (int size) {
	List<Person> ret = new ArrayList<>();
	
	String firstNames[] = {"Mary","Patricia","Linda","Barbara","Elizabeth","James","John","Robert","Michael","William"};
	String lastNames[] = {"Smith","Jones","Taylor","Williams","Brown","Davies","Evans","Wilson","Thomas","Roberts"};
	
	Random randomGenerator=new Random();
	for (int i=0; i<size; i++) {
		Person person=new Person();
		person.setId(i);
		person.setFirstName(firstNames[randomGenerator.nextInt(10)]);
		person.setLastName(lastNames[randomGenerator.nextInt(10)]);
		person.setSalary(randomGenerator.nextInt(100000));
		person.setCoeficient(randomGenerator.nextDouble()*10);
		Calendar calendar=Calendar.getInstance();
		calendar.add(Calendar.YEAR, -randomGenerator.nextInt(30));
		Date birthDate=calendar.getTime();
		person.setBirthDate(birthDate);
		
		ret.add(person);
	}
	
	return ret;
}
 
Example 3
Project: Java-9-Concurrency-Cookbook-Second-Edition   File: PersonGenerator.java   View Source Code Vote up 6 votes
public static List<Person> generatePersonList (int size) {
	List<Person> ret = new ArrayList<>();
	
	String firstNames[] = {"Mary","Patricia","Linda","Barbara","Elizabeth","James","John","Robert","Michael","William"};
	String lastNames[] = {"Smith","Jones","Taylor","Williams","Brown","Davies","Evans","Wilson","Thomas","Roberts"};
	
	Random randomGenerator=new Random();
	for (int i=0; i<size; i++) {
		Person person=new Person();
		person.setId(i);
		person.setFirstName(firstNames[randomGenerator.nextInt(10)]);
		person.setLastName(lastNames[randomGenerator.nextInt(10)]);
		person.setSalary(randomGenerator.nextInt(100000));
		person.setCoeficient(randomGenerator.nextDouble()*10);
		Calendar calendar=Calendar.getInstance();
		calendar.add(Calendar.YEAR, -randomGenerator.nextInt(30));
		Date birthDate=calendar.getTime();
		person.setBirthDate(birthDate);
		
		ret.add(person);
	}
	
	return ret;
}
 
Example 4
Project: GoalsAndHabits   File: HabitTest.java   View Source Code Vote up 6 votes
public void testGetEventsCompleted() {
    Habit habit = new Habit("TestTitle","TestReason",new Date());
    HashSet<Integer> schedule = new HashSet<>();
    schedule.add(Calendar.MONDAY);
    schedule.add(Calendar.WEDNESDAY);
    schedule.add(Calendar.FRIDAY);
    habit.setSchedule(schedule);
    Calendar c = Calendar.getInstance();
    while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY){
        c.add(Calendar.DAY_OF_YEAR,1);
    }
    c.add(Calendar.DAY_OF_YEAR,7);
    HabitEvent eventOnMonday = new HabitEvent(c.getTime());
    c.add(Calendar.DAY_OF_YEAR,1);
    HabitEvent eventOnTuesday = new HabitEvent(c.getTime());
    c.add(Calendar.DAY_OF_YEAR,-5);
    HabitEvent eventBeforeStartDate = new HabitEvent(c.getTime());
    habit.addHabitEvent(eventOnMonday);
    habit.addHabitEvent(eventOnTuesday);
    habit.addHabitEvent(eventBeforeStartDate);
    assertEquals(1,habit.getEventsCompleted());
}
 
Example 5
Project: neoscada   File: QueryControlView.java   View Source Code Vote up 6 votes
protected void changeRequest ( final int secondsOffset, final int secondsScale )
{
    final Calendar start = Calendar.getInstance ();
    start.setTimeInMillis ( this.requestParameters.getStartTimestamp () );

    final Calendar end = Calendar.getInstance ();
    end.setTimeInMillis ( this.requestParameters.getEndTimestamp () );

    start.add ( Calendar.SECOND, secondsOffset );
    end.add ( Calendar.SECOND, secondsOffset );

    long diff = end.getTimeInMillis () - start.getTimeInMillis ();
    diff = diff / 1000;
    diff += secondsScale;
    if ( diff < 0 )
    {
        diff = 0;
    }
    diff *= 1000;
    end.setTimeInMillis ( start.getTimeInMillis () + diff );

    this.requestParameters = new QueryParameters ( start.getTimeInMillis (), end.getTimeInMillis (), this.requestParameters.getNumberOfEntries () );
    updateRequestParameters ();
}
 
Example 6
Project: xtf   File: XTFKeyStore.java   View Source Code Vote up 6 votes
public void addSelfSignedCertificate(String certificateAlias, String dn, String password) {
	try {
		KeyPair keys = generateKeyPair();

		Calendar start = Calendar.getInstance();
		Calendar expiry = Calendar.getInstance();
		expiry.add(Calendar.YEAR, 1);
		X500Name name = new X500Name(dn);
		X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(name, BigInteger.ONE,
				start.getTime(), expiry.getTime(), name, SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded()));
		ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(new BouncyCastleProvider()).build(keys.getPrivate());
		X509CertificateHolder holder = certificateBuilder.build(signer);
		Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);

		Entry entry = new PrivateKeyEntry(keys.getPrivate(), new Certificate[]{ cert });
		keystore.setEntry(certificateAlias, entry, new PasswordProtection(password.toCharArray()));
	} catch (GeneralSecurityException | OperatorCreationException ex) {
		throw new RuntimeException("Unable to generate self-signed certificate", ex);
	}
}
 
Example 7
Project: neoscada   File: QueryBufferTest.java   View Source Code Vote up 5 votes
private Date timestampMs ( final Calendar base, final int ms )
{
    final Calendar c = (Calendar)base.clone ();
    c.add ( Calendar.MILLISECOND, ms );
    return c.getTime ();
}
 
Example 8
Project: AnotherRSS   File: MainActivity.java   View Source Code Vote up 5 votes
@Override
protected Void doInBackground(Void... voids) {
    Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    int autodeleteDays = mPreferences.getInt("autodelete", AnotherRSS.Config.DEFAULT_autodelete);
    if (autodeleteDays < 1) return null;

    Date date = new Date();
    c.setTime(date);
    c.add(Calendar.DAY_OF_MONTH, -1 * autodeleteDays);
    date = c.getTime();
    String dateStr = FeedContract.dbFriendlyDate(date);

    String where = FeedContract.Feeds.COLUMN_Date + "<? and "
            + FeedContract.Feeds.COLUMN_Flag + "<> ?";

    ContentValues values = new ContentValues();
    values.put(FeedContract.Feeds.COLUMN_Deleted, FeedContract.Flag.DELETED);

    getContentResolver().update(
            FeedContentProvider.CONTENT_URI,
            values,
            where,
            new String[]{dateStr, Integer.toString(FeedContract.Flag.FAVORITE)}
    );

    return null;
}
 
Example 9
Project: Spring-Boot-MongoDB-JWT   File: JsonWebTokenService.java   View Source Code Vote up 5 votes
@Override
public String getToken(final String username, final String password) {
    if (username == null || password == null) {
        return null;
    }
    final User user = (User) userDetailsService.loadUserByUsername(username);
    Map<String, Object> tokenData = new HashMap<>();
    if (password.equals(user.getPassword())) {
        tokenData.put("clientType", "user");
        tokenData.put("userID", user.getId());
        tokenData.put("username", user.getUsername());
        tokenData.put("token_create_date", LocalDateTime.now());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, tokenExpirationTime);
        tokenData.put("token_expiration_date", calendar.getTime());
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setExpiration(calendar.getTime());
        jwtBuilder.setClaims(tokenData);
        return jwtBuilder.signWith(SignatureAlgorithm.HS512, tokenKey).compact();

    } else {
        throw new ServiceException("Authentication error", this.getClass().getName());
    }
}
 
Example 10
Project: jaer   File: BlurringTunnelTracker.java   View Source Code Vote up 5 votes
private void setTimers(){
	//reset the computer every day at 4:00
	Calendar nextReset = new GregorianCalendar();
	nextReset.add(Calendar.DAY_OF_MONTH, 1);
	nextReset.set(Calendar.HOUR_OF_DAY, 4);
	nextReset.set(Calendar.MINUTE, 00);
	TimerTask resetTask = new Resetter();
	resetTimer.schedule(resetTask, nextReset.getTime());
}
 
Example 11
Project: Hydrograph   File: DateFunctions.java   View Source Code Vote up 5 votes
/**
 * Returns date with {@code hours} added to {@code date}
 *
 * @param date       the date to which hours are to be added
 * @param hours hours to be added to given {@code date}
 * @return date after adding {@code hours} to {@code date}
 * if {@code date} is null then return null
 */
public static Date addHoursToDate(Date date, int hours) {
    if(date == null)
        return null;
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.HOUR_OF_DAY, hours);
    return c.getTime();
}
 
Example 12
Project: TechnicalAnalysisTool   File: DateUtil.java   View Source Code Vote up 5 votes
/**
 * Return if the date is the first Day of the year
 * @param countryName the country name
 * @param calendar Calendar object in query
 * @return true if it is otherwise return false
 */
public static boolean isFirstDayofYear(Calendar calendar, String countryName){
    Calendar local =  (Calendar)calendar.clone();
    if(local == null)
        return false;

    if (isWeekend(local)){
        return false;
    }
    
    if (isPublicHoliday(local, countryName)){
        return false;
    }
        
    int dayOfYear = local.get(Calendar.DAY_OF_YEAR);
    if (dayOfYear == 1){
        return true;
    }else{
        while(local.get(Calendar.DAY_OF_YEAR) != 1) {
            local.add(Calendar.DAY_OF_YEAR, -1);
            if(!isPublicHoliday(local, countryName) && !isWeekend(local)){
                return false;
            }
        }
        //See if the first day of the month is public holiday or not
        if (isPublicHoliday(local,countryName) || isWeekend(local)){
            return true;
        }else{
            return false;
        }
    }
}
 
Example 13
Project: NotifyTools   File: CalcLunar.java   View Source Code Vote up 5 votes
public String ChineseTwentyFourNextDay(Date _date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(_date);
    Date baseDateAndTime = new Date(0, 0, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
    Calendar basecalendar = Calendar.getInstance();
    basecalendar.setTime(baseDateAndTime);
    Date newDate;
    double num;
    int y;
    String tempStr = "";

    y = _date.getYear() + 1900;

    for (int i = 1; i <= 24; i++) {
        num = 525948.76 * (y - 1900) + Consts.sTermInfo[i - 1];

        basecalendar.setTime(baseDateAndTime);
        basecalendar.add(Calendar.MINUTE, (int) (num));//按分钟计算
        if (basecalendar.get(Calendar.DAY_OF_YEAR) > calendar.get(Calendar.DAY_OF_YEAR)) {

            tempStr = String.format("%s[%s]", Consts.SolarTerm[i - 1], sdf.format(basecalendar.getTime()));
            break;

        }
    }
    return tempStr;
}
 
Example 14
Project: belling-spring-rabbitmq   File: TimeUtils.java   View Source Code Vote up 5 votes
public static Date getSecond(int second) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.SECOND, second);
		Date time = calendar.getTime();

		return time;
	}
 
Example 15
Project: Bartout   File: UserStatus.java   View Source Code Vote up 4 votes
/**
 *
 * @param level alcohol level
 * @param increase if true, it gets only a moment, when the level is increasing, else only if decreasing
 * @return
 */
private List<Calendar>  getMomentsOfSpecificAlcoholLevel(double level, boolean increase) {
    List<Calendar> calendars = new ArrayList<Calendar>();
    double alcoholVolume = 0;
    boolean eventShouldHappen = true;
    for(Consumption consumption : consumptions){
        double alcoholVolumeBeforeBreakDown = alcoholVolume + getAlcoholVolumeOfConsumption(consumption);
        if(alcoholVolumeBeforeBreakDown>=level && eventShouldHappen){
            if (increase){
                calendars.add(consumption.getConsumptionTime());
                eventShouldHappen = false;
            }else{
                int durationOfBreakDownInSecOfDiff = (int)Math.round(getDurationOfBreakDown(alcoholVolumeBeforeBreakDown-level)*60*60);
                Calendar consumptionTimeWithDurationOfBreakDown = Calendar.getInstance();
                consumptionTimeWithDurationOfBreakDown.setTime(consumption.getConsumptionTime().getTime());
                consumptionTimeWithDurationOfBreakDown.add(Calendar.SECOND,durationOfBreakDownInSecOfDiff);
                boolean hasNext = (consumptions.indexOf(consumption)<consumptions.size()-1);
                if(hasNext){
                    Consumption next = consumptions.get(consumptions.indexOf(consumption));
                    if (consumptionTimeWithDurationOfBreakDown.before(next.getConsumptionTime())){
                        calendars.add(consumptionTimeWithDurationOfBreakDown);
                        eventShouldHappen = false;
                    }
                }else{
                    calendars.add(consumptionTimeWithDurationOfBreakDown);
                    eventShouldHappen = false;
                }
            }
        }
        double durationBetweenStartAndEndInSec = getDurationBetweenOneAndNextConsumption(consumption);
        double alcoholBreakDown = getAlcoholBreakDownOfDuration(durationBetweenStartAndEndInSec);
        double alcoholVolumeMinusBreakDown = alcoholVolumeBeforeBreakDown-alcoholBreakDown;
        if (alcoholVolumeMinusBreakDown<0){
            alcoholVolumeMinusBreakDown=0;
        }
        if (alcoholVolumeBeforeBreakDown>level && level > alcoholVolumeMinusBreakDown){
            eventShouldHappen = true;
        }
        alcoholVolume=alcoholVolumeMinusBreakDown;
    }
    return calendars;
}
 
Example 16
Project: Log4Reports   File: DateUtil.java   View Source Code Vote up 4 votes
public static String getNewDate(int days){
	Calendar cal = Calendar.getInstance();
       cal.setTime(new Date());
       cal.add(Calendar.DATE, days); 
       return (new SimpleDateFormat("yyyy-MM-dd")).format(cal.getTime());
}
 
Example 17
Project: mycat-src-1.6.1-RELEASE   File: PartitionByHotDateTest.java   View Source Code Vote up 4 votes
@Test
	public void test()  {
PartitionByHotDate partition = new PartitionByHotDate();
		
		partition.setDateFormat("yyyy-MM-dd");
		partition.setsLastDay("10");
		partition.setsPartionDay("1");

		partition.init();
		
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

		Calendar cDate = Calendar.getInstance();
		cDate.set(Calendar.MONTH, cDate.get(Calendar.MONTH));
		cDate.set(Calendar.DATE, cDate.get(Calendar.DATE));
		Assert.assertEquals(true, 0 == partition.calculate(dateFormat.format(cDate.getTime())));
		
		cDate = Calendar.getInstance();
		cDate.add(Calendar.DATE,-5);
		System.err.println(dateFormat.format(cDate.getTime()));
		Assert.assertEquals(true, 0 == partition.calculate(dateFormat.format(cDate.getTime())));
		
		cDate = Calendar.getInstance();
		cDate.add(Calendar.DATE,-11);
		System.err.println(dateFormat.format(cDate.getTime()));
		Assert.assertEquals(true, 2 == partition.calculate(dateFormat.format(cDate.getTime())));
		
		cDate = Calendar.getInstance();
		cDate.add(Calendar.DATE, -21);
		System.err.println(dateFormat.format(cDate.getTime()));
		Assert.assertEquals(true, 12 == partition.calculate(dateFormat.format(cDate.getTime())));

		cDate = Calendar.getInstance();
		cDate.add(Calendar.DATE,-5);
		System.err.println(dateFormat.format(cDate.getTime()));
		Assert.assertEquals(true, 0 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[0]);
		
		cDate = Calendar.getInstance();
		cDate.add(Calendar.DATE,-11);
		System.err.println(dateFormat.format(cDate.getTime()));
		Assert.assertEquals(true, 0 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[0]);
		Assert.assertEquals(true, 1 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[1]);
		Assert.assertEquals(true, 2 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[2]);

		cDate = Calendar.getInstance();
		cDate.add(Calendar.DATE, -21);
		System.err.println(dateFormat.format(cDate.getTime()));
		Assert.assertEquals(true, 0 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[0]);
		Assert.assertEquals(true, 1 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[1]);
		Assert.assertEquals(true, 2 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[2]);
		Assert.assertEquals(true, 12 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime()))[12]);
		Assert.assertEquals(true, 13 == partition.calculateRange(dateFormat.format(cDate.getTime()),dateFormat.format(Calendar.getInstance().getTime())).length);

	}
 
Example 18
Project: boohee_v5.6   File: DateFormatUtils.java   View Source Code Vote up 4 votes
public static Date getWeek(String dateString, int weekNum) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(string2date(dateString, "yyyy-MM-dd"));
    cal.add(4, weekNum);
    return cal.getTime();
}
 
Example 19
Project: mumu   File: DateUtils.java   View Source Code Vote up 3 votes
/**
 * 计算 hour 小时后的时间
 * 
 * @param date
 * @param hour
 * @return
 */
public static Date addHour(Date date, int hour) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(date);
	calendar.add(Calendar.HOUR, hour);
	return calendar.getTime();
}
 
Example 20
Project: xbin-store   File: DateUtils.java   View Source Code Vote up 3 votes
/**
 * 判断开始时间和结束时间,是否超出了当前时间的一定的间隔数限制 如:开始时间和结束时间,不能超出距离当前时间90天
 *
 * @param startDate
 *            开始时间
 * @param endDate
 *            结束时间按
 * @param interval
 *            间隔数
 * @param dateUnit
 *            单位(如:月,日),参照Calendar的时间单位
 * @return
 */
public static boolean isOverIntervalLimit(Date startDate, Date endDate, int interval, int dateUnit) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(new Date());
	cal.add(dateUnit, interval * (-1));
	Date curDate = getDayStart(cal.getTime());
	if (getDayStart(startDate).compareTo(curDate) < 0 || getDayStart(endDate).compareTo(curDate) < 0) {
		return true;
	}
	return false;
}