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

The following are Jave code examples for showing how to use setTime() 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: unitimes   File: MakeAssignmentsForClassEvents.java   View Source Code Vote up 7 votes
public int getDaysCode(Event event) {
    int daysCode = 0;
    for (Iterator i=event.getMeetings().iterator();i.hasNext();) {
        Meeting meeting = (Meeting)i.next();
        Calendar date = Calendar.getInstance(Locale.US);
        date.setTime(meeting.getMeetingDate());
        switch (date.get(Calendar.DAY_OF_WEEK)) {
        case Calendar.MONDAY : daysCode |= Constants.DAY_CODES[Constants.DAY_MON]; break;
        case Calendar.TUESDAY : daysCode |= Constants.DAY_CODES[Constants.DAY_TUE]; break;
        case Calendar.WEDNESDAY : daysCode |= Constants.DAY_CODES[Constants.DAY_WED]; break;
        case Calendar.THURSDAY : daysCode |= Constants.DAY_CODES[Constants.DAY_THU]; break;
        case Calendar.FRIDAY : daysCode |= Constants.DAY_CODES[Constants.DAY_FRI]; break;
        case Calendar.SATURDAY : daysCode |= Constants.DAY_CODES[Constants.DAY_SAT]; break;
        case Calendar.SUNDAY : daysCode |= Constants.DAY_CODES[Constants.DAY_SUN]; break;
        }
    }
    return daysCode;
}
 
Example 2
Project: JAVA-   File: DateUtil.java   View Source Code Vote up 7 votes
/**
 * 间隔天数
 * 
 * @param startDate
 * @param endDate
 * @return
 */
public static final Integer getDayBetween(Date startDate, Date endDate) {
	Calendar start = Calendar.getInstance();
	start.setTime(startDate);
	start.set(Calendar.HOUR_OF_DAY, 0);
	start.set(Calendar.MINUTE, 0);
	start.set(Calendar.SECOND, 0);
	start.set(Calendar.MILLISECOND, 0);
	Calendar end = Calendar.getInstance();
	end.setTime(endDate);
	end.set(Calendar.HOUR_OF_DAY, 0);
	end.set(Calendar.MINUTE, 0);
	end.set(Calendar.SECOND, 0);
	end.set(Calendar.MILLISECOND, 0);

	long n = end.getTimeInMillis() - start.getTimeInMillis();
	return (int) (n / (60 * 60 * 24 * 1000l));
}
 
Example 3
Project: Pluto-Android   File: DateUtil.java   View Source Code Vote up 7 votes
/**
 * 年月日
 * @param date
 * @return
 */
public static String getDay(Date date) {
	TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone
	Calendar calendar = Calendar.getInstance(t);
	if (date == null) {
		calendar.setTimeInMillis(System.currentTimeMillis());
	} else {
		calendar.setTime(date);
	}
	int year = calendar.get(Calendar.YEAR);
	int month = calendar.get(Calendar.MONTH) + 1;
	int day = calendar.get(Calendar.DAY_OF_MONTH);

	String time = year + "-" + (month < 10 ? "0" : "") + month + '-' + (day < 10 ? "0" : "") + day;
	return time;
}
 
Example 4
Project: Minimal-Todo   File: ReminderActivity.java   View Source Code Vote up 6 votes
private Date addTimeToDate(int mins){
    Date date = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.MINUTE, mins);
    return calendar.getTime();
}
 
Example 5
Project: mycat-src-1.6.1-RELEASE   File: PartitionByRangeDateHashTest.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws ParseException
{

    Map map=new HashMap<>()  ;
    Date beginDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-01-04 00:00:01");
    for (int i = 0; i < 60*60*24*10; i++)
    {


        Calendar cal = Calendar.getInstance();
        cal.setTime(beginDate);
       cal.add(Calendar.SECOND, 1);
        beginDate = cal.getTime();
        int hash = hash(beginDate.getTime(), 3);
        if(map.containsKey(hash))
        {
        map.put(hash,    (int)map.get(hash)+1);
        } else
        {
            map.put(hash,1);
        }
      //  System.out.println(hash);
    }


    System.out.println(map.values());
}
 
Example 6
Project: microservices-sample-project   File: EmailVerification.java   View Source Code Vote up 6 votes
public EmailVerification calculateExpiryDate() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Timestamp(cal.getTime().getTime()));
    cal.add(Calendar.MINUTE, EXPIRATION);
    this.expiryDate = new Date(cal.getTime().getTime());
    return this;
}
 
Example 7
Project: opencps-v2   File: DateTimeUtils.java   View Source Code Vote up 6 votes
public static int getYearFromDate(Date date) {
	int year = 1990;

	if (date != null) {
		Calendar calendar = Calendar.getInstance();

		calendar.setTime(date);
		year = calendar.get(Calendar.YEAR);

		calendar.setTime(date);
		year = calendar.get(Calendar.YEAR);
	}

	return year;
}
 
Example 8
Project: mumu   File: DateUtils.java   View Source Code Vote up 6 votes
/**
 * 得到当前年起始时间
 * 
 * @param date
 * @return
 */
public static Date getYearStart(Date date) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(date);
	calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
	calendar.set(Calendar.MONTH, 0);
	calendar.set(Calendar.DAY_OF_MONTH, 1);
	calendar.set(Calendar.HOUR_OF_DAY, 0);
	calendar.set(Calendar.MINUTE, 0);
	calendar.set(Calendar.SECOND, 0);
	calendar.set(Calendar.MILLISECOND, 0);
	return calendar.getTime();
}
 
Example 9
Project: marathonv5   File: DailySalesHeatMapFacadeREST.java   View Source Code Vote up 6 votes
private HashMap<String, Long> runBaseQuery(Date date){
    Calendar cal = Calendar.getInstance();
    long DIFF, TIME = System.currentTimeMillis(), START_TIME = System.currentTimeMillis();
    Query baseQuery = em.createQuery(BASE_QUERY);
    HashMap<String, Long> result = new HashMap<String, Long>();
    {
        cal.setTime(date);
        int dayMin = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        int dayMax = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, dayMin);
        Parameter<Date> p1 = baseQuery.getParameter("oldStartDate", Date.class);
        baseQuery.setParameter(p1, cal.getTime());
        cal.set(Calendar.DAY_OF_MONTH, dayMax);
        Parameter<Date> p2 = baseQuery.getParameter("oldEndDate", Date.class);
        baseQuery.setParameter(p2, cal.getTime());

        List<Object[]> resultList = baseQuery.getResultList();

        DIFF = (System.currentTimeMillis() - TIME);
        System.out.println("    Q TIME = "+DIFF+"ms");

        for (int i=0; i < resultList.size(); i++){
            Object o[] = resultList.get(i);
            result.put((String)o[1],(Long)o[0]);
        }
    }
    return result;
}
 
Example 10
Project: lams   File: TimeOfDay.java   View Source Code Vote up 6 votes
/**
 * Create a TimeOfDay from the given date (at the zero-second), in the system default TimeZone.
 * 
 * @param dateTime The java.util.Date from which to extract Hour and Minute.
 * @param tz The TimeZone from which relate Hour and Minute for the given date.  If null, system default
 * TimeZone will be used.
 */
public static TimeOfDay hourAndMinuteFromDate(Date dateTime, TimeZone tz) {
    if (dateTime == null)
        return null;
    Calendar cal = Calendar.getInstance();
    cal.setTime(dateTime);
    if(tz != null)
        cal.setTimeZone(tz);
    
    return new TimeOfDay(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
}
 
Example 11
Project: CodeBroker   File: TimeUtil.java   View Source Code Vote up 6 votes
public static boolean isToday(Date date) {
    Calendar dt1 = getCalendar();
    Calendar dt2 = getCalendar();
    dt2.setTime(date);
    if ((dt1.get(Calendar.MONTH) == dt2.get(Calendar.MONTH)) && (dt1.get(Calendar.DAY_OF_MONTH) == dt2.get(Calendar.DAY_OF_MONTH))) {
        return true;
    }
    return false;
}
 
Example 12
Project: Unofficial-Ups   File: UpcUniversityInfoRepository.java   View Source Code Vote up 6 votes
@Override
public Observable<String> reserve(ReserveOption option) {
    DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy HHmm");
    String startDate = dateFormat.format(option.getDatetime());
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(option.getDatetime());
    calendar.add(Calendar.HOUR,option.getDuration());
    String endDate = dateFormat.format(calendar.getTime());
    String duration = String.valueOf(option.getDuration());

    return sessionRepo.getSession().flatMap( s ->
            remoteSource.reserve(option.getCode(),option.getName(),startDate,endDate,duration,s.getUserCode(),s.getToken()));
}
 
Example 13
Project: xlight_android_native   File: DateUtil.java   View Source Code Vote up 6 votes
public static void main3(String[] args) throws ParseException {
    Date startDateTime = DateUtil.parserToSecond("2013-05-13 14:02:42");
    Date endDateTime = DateUtil.parserToSecond("2013-05-17 12:02:42");
    String startHHmmStr = DateUtil.formatToHHmm(startDateTime);
    String startDayStr = DateUtil.formatToDay(startDateTime);
    String endHHmmStr = DateUtil.formatToHHmm(endDateTime);
    String endDayStr = DateUtil.formatToDay(endDateTime);
    // 得到二个日期间的间隔天数
    long day = (endDateTime.getTime() - startDateTime.getTime())
            / (24 * 60 * 60 * 1000);
    // 开始那天
    String tStart = startDayStr + "==" + startHHmmStr + "-"
            + DateUtil.formatToHHmm(DateUtil.getCurrEnd(startDateTime));
    System.out.println(tStart);

    // 中间那些天
    for (int i = 0; i < day; i++) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDateTime);
        calendar.roll(Calendar.DATE, i + 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(sdf.format(calendar.getTime()));
        String tMiddle = DateUtil.formatToDay(date) + "=="
                + DateUtil.formatToHHmm(DateUtil.getCurrStart(date)) + "-"
                + DateUtil.formatToHHmm(DateUtil.getCurrEnd(date));
        System.out.println(i + 1 + "--" + tMiddle);
    }

    // 结束那天
    String tEnd = endDayStr + "=="
            + DateUtil.formatToHHmm(DateUtil.getCurrStart(endDateTime))
            + "-" + endHHmmStr;
    System.out.println(tEnd);

}
 
Example 14
Project: lams   File: CronSequenceGenerator.java   View Source Code Vote up 6 votes
/**
 * Get the next {@link Date} in the sequence matching the Cron pattern and
 * after the value provided. The return value will have a whole number of
 * seconds, and will be after the input value.
 * @param date a seed value
 * @return the next value matching the pattern
 */
public Date next(Date date) {
	/*
	The plan:

	1 Round up to the next whole second

	2 If seconds match move on, otherwise find the next match:
	2.1 If next match is in the next minute then roll forwards

	3 If minute matches move on, otherwise find the next match
	3.1 If next match is in the next hour then roll forwards
	3.2 Reset the seconds and go to 2

	4 If hour matches move on, otherwise find the next match
	4.1 If next match is in the next day then roll forwards,
	4.2 Reset the minutes and seconds and go to 2

	...
	*/

	Calendar calendar = new GregorianCalendar();
	calendar.setTimeZone(this.timeZone);
	calendar.setTime(date);

	// First, just reset the milliseconds and try to calculate from there...
	calendar.set(Calendar.MILLISECOND, 0);
	long originalTimestamp = calendar.getTimeInMillis();
	doNext(calendar, calendar.get(Calendar.YEAR));

	if (calendar.getTimeInMillis() == originalTimestamp) {
		// We arrived at the original timestamp - round up to the next whole second and try again...
		calendar.add(Calendar.SECOND, 1);
		doNext(calendar, calendar.get(Calendar.YEAR));
	}

	return calendar.getTime();
}
 
Example 15
Project: GitHub   File: DateFieldTest9.java   View Source Code Vote up 6 votes
public void test_kr_2() throws Exception {
    Entity vo = JSON.parseObject("{\"date\":\"2016년5월06일\"}", Entity.class);

    Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale);
    calendar.setTime(vo.date);
    Assert.assertEquals(2016, calendar.get(Calendar.YEAR));
    Assert.assertEquals(4, calendar.get(Calendar.MONTH));
    Assert.assertEquals(6, calendar.get(Calendar.DAY_OF_MONTH));
    Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
    Assert.assertEquals(0, calendar.get(Calendar.MINUTE));
    Assert.assertEquals(0, calendar.get(Calendar.SECOND));
    Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND));
}
 
Example 16
Project: unitimes   File: EventRoomAvailabilityBackend.java   View Source Code Vote up 5 votes
public static TreeSet<MeetingConflictInterface> generateUnavailabilityMeetings(Location location, List<Integer> dates, int startSlot, int endSlot) {
	if (location.getEventAvailability() == null || location.getEventAvailability().length() != Constants.SLOTS_PER_DAY * Constants.DAY_CODES.length) return null;

	TreeSet<MeetingConflictInterface> ret = new TreeSet<MeetingConflictInterface>();
	
	ResourceInterface resource = new ResourceInterface();
	resource.setType(ResourceType.ROOM);
	resource.setId(location.getUniqueId());
	resource.setName(location.getLabel());
	resource.setSize(location.getCapacity());
	resource.setRoomType(location.getRoomTypeLabel());
	resource.setBreakTime(location.getEffectiveBreakTime());
	resource.setMessage(location.getEventMessage());
	resource.setIgnoreRoomCheck(location.isIgnoreRoomCheck());
	resource.setDisplayName(location.getDisplayName());
	
	Calendar calendar = Calendar.getInstance();
       for (int day = 0; day < Constants.DAY_CODES.length; day++)
       	for (int startTime = 0; startTime < Constants.SLOTS_PER_DAY; ) {
       		if (location.getEventAvailability().charAt(day * Constants.SLOTS_PER_DAY + startTime) != '1') { startTime++; continue; }
       		int endTime = startTime + 1;
       		while (endTime < Constants.SLOTS_PER_DAY && location.getEventAvailability().charAt(day * Constants.SLOTS_PER_DAY + endTime) == '1') endTime++;
       		if (startTime < endSlot && startSlot < endTime) {
           		calendar.setTime(location.getSession().getEventBeginDate());
           		int dayOfYear = CalendarUtils.date2dayOfYear(location.getSession().getSessionStartYear(), calendar.getTime());
           		
           		do {
           			if (dates.contains(dayOfYear)) {
               			int dayOfWeek = -1;
               			switch (calendar.get(Calendar.DAY_OF_WEEK)) {
               			case Calendar.MONDAY: dayOfWeek = Constants.DAY_MON; break;
               			case Calendar.TUESDAY: dayOfWeek = Constants.DAY_TUE; break;
               			case Calendar.WEDNESDAY: dayOfWeek = Constants.DAY_WED; break;
               			case Calendar.THURSDAY: dayOfWeek = Constants.DAY_THU; break;
               			case Calendar.FRIDAY: dayOfWeek = Constants.DAY_FRI; break;
               			case Calendar.SATURDAY: dayOfWeek = Constants.DAY_SAT; break;
               			case Calendar.SUNDAY: dayOfWeek = Constants.DAY_SUN; break;
               			}
               			
               			if (day == dayOfWeek) {
                   			MeetingConflictInterface m = new MeetingConflictInterface();
               				m.setName(MESSAGES.unavailableEventDefaultName());
               				m.setType(EventInterface.EventType.Unavailabile);
                       		m.setStartSlot(startTime);
                       		m.setEndSlot(endTime);
                       		m.setDayOfWeek(dayOfWeek);
                       		m.setMeetingDate(calendar.getTime());
                       		m.setDayOfYear(dayOfYear);
                       		m.setLocation(resource);
                       		ret.add(m);
               			}
           			}
           			calendar.add(Calendar.DAY_OF_YEAR, 1); dayOfYear++;
           		} while (!calendar.getTime().after(location.getSession().getEventEndDate()));        			
       		}
       		startTime = endTime;
       	}
	return ret;
}
 
Example 17
Project: TaipeiTechRefined   File: ActivityCheckReceiver.java   View Source Code Vote up 5 votes
@Override
        protected HashMap<ActivityInfo, Bitmap> doInBackground(Void... params) {
//            if (WifiUtility.isWifiOpen(context) && WifiUtility.isNetworkAvailable(context)) {
//                try {
//                    ActivityList activityList = ActivityConnector.getActivityList(context);
//                    Model.getInstance().setActivityArray(activityList);
//                    Model.getInstance().saveActivityArray();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }

            if (!needToCheck(context)){
                return null;
            }
            HashMap<ActivityInfo, Bitmap> result = new HashMap<>();
            Calendar calendar = Calendar.getInstance();
            ArrayList<ActivityInfo> activityInfos = Model.getInstance()
                    .getActivityArray();
            if (activityInfos == null) {
                return null;
            }
            for (ActivityInfo activity : activityInfos) {
                Calendar temp = Calendar.getInstance();
                temp.setTime(activity.getStartDate());
                temp.add(Calendar.DAY_OF_MONTH, -1);
                Calendar temp2 = Calendar.getInstance();
                temp2.setTime(activity.getStartDate());
                if (dateEquals(calendar, temp)
                        || dateEquals(calendar, temp2)) {
                    Bitmap bitmap = null;
                    try {
                        if (!TextUtils.isEmpty(activity.getImage())) {
                            String file_path = context.getCacheDir().getPath()
                                    + "/" + activity.getImage();
                            bitmap = BitmapUtility.loadBitmap(context, file_path);
                        } else {
                            bitmap = BitmapUtility.loadBitmap(context, R.drawable.no_image);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    result.put(activity, bitmap);
                }
            }
            return result;
        }
 
Example 18
Project: logistimo-web-service   File: LocalDateUtil.java   View Source Code Vote up 5 votes
public static int getCurrentYear() {
  Calendar cal = GregorianCalendar.getInstance();
  cal.setTime(new Date());
  return cal.get(Calendar.YEAR);
}
 
Example 19
Project: Backmemed   File: GuiMainMenu.java   View Source Code Vote up 5 votes
/**
 * Adds the buttons (and other controls) to the screen in question. Called
 * when the GUI is displayed and when the window resizes, the buttonList is
 * cleared beforehand.
 */
public void initGui() {
	this.viewportTexture = new DynamicTexture(256, 256);
	this.backgroundTexture = this.mc.getTextureManager().getDynamicTextureLocation("background",
			this.viewportTexture);
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(new Date());

	if (calendar.get(2) + 1 == 12 && calendar.get(5) == 24) {
		this.splashText = "Merry X-mas!";
	} else if (calendar.get(2) + 1 == 1 && calendar.get(5) == 1) {
		this.splashText = "Happy new year!";
	} else if (calendar.get(2) + 1 == 10 && calendar.get(5) == 31) {
		this.splashText = "OOoooOOOoooo! Spooky!";
	} else if (calendar.get(2) + 1 == 9 && calendar.get(5) == 27) {
		this.splashText = "Happy Birthday, Sgt. Pepper!";
	} else if (calendar.get(2) + 1 == 5 && calendar.get(5) == 28) {
		this.splashText = "Happy Birthday, x0XP!";
	}

	int i = 24;
	int j = this.height / 4 + 48;

	if (this.mc.isDemo()) {
		this.addDemoButtons(j, 24);
	} else {
		this.addSingleplayerMultiplayerButtons(j, 24);
	}

	this.buttonList.add(new GuiButton(0, this.width / 2 - 100, j + 72 + 12, 98, 20,
			I18n.format("menu.options", new Object[0])));
	this.buttonList.add(
			new GuiButton(4, this.width / 2 + 2, j + 72 + 12, 98, 20, I18n.format("menu.quit", new Object[0])));
	this.buttonList.add(new GuiButtonLanguage(5, this.width / 2 - 124, j + 72 + 12));

	synchronized (this.threadLock) {
		this.openGLWarning1Width = this.fontRendererObj.getStringWidth(this.openGLWarning1);
		this.openGLWarning2Width = this.fontRendererObj.getStringWidth(this.openGLWarning2);
		int k = Math.max(this.openGLWarning1Width, this.openGLWarning2Width);
		this.openGLWarningX1 = (this.width - k) / 2;
		this.openGLWarningY1 = ((GuiButton) this.buttonList.get(0)).yPosition - 24;
		this.openGLWarningX2 = this.openGLWarningX1 + k;
		this.openGLWarningY2 = this.openGLWarningY1 + 24;
	}

	this.mc.setConnectedToRealms(false);

	if (Minecraft.getMinecraft().gameSettings.getOptionOrdinalValue(GameSettings.Options.REALMS_NOTIFICATIONS)
			&& !this.hasCheckedForRealmsNotification) {
		RealmsBridge realmsbridge = new RealmsBridge();
		this.realmsNotification = realmsbridge.getNotificationScreen(this);
		this.hasCheckedForRealmsNotification = true;
	}

	if (this.areRealmsNotificationsEnabled()) {
		this.realmsNotification.setGuiSize(this.width, this.height);
		this.realmsNotification.initGui();
	}

	if (Reflector.NotificationModUpdateScreen_init.exists()) {
		this.modUpdateNotification = (GuiScreen) Reflector.call(Reflector.NotificationModUpdateScreen_init,
				new Object[] { this, this.modButton });
	}
}
 
Example 20
Project: OpenJSharp   File: DurationImpl.java   View Source Code Vote up 4 votes
/**
 * Adds this duration to a {@link Date} object.
 *
 * <p>
 * The given date is first converted into
 * a {@link java.util.GregorianCalendar}, then the duration
 * is added exactly like the {@link #addTo(Calendar)} method.
 *
 * <p>
 * The updated time instant is then converted back into a
 * {@link Date} object and used to update the given {@link Date} object.
 *
 * <p>
 * This somewhat redundant computation is necessary to unambiguously
 * determine the duration of months and years.
 *
 * @param date
 *      A date object whose value will be modified.
 * @throws NullPointerException
 *      if the date parameter is null.
 */
public void addTo(Date date) {
    Calendar cal = new GregorianCalendar();
    cal.setTime(date); // this will throw NPE if date==null
    this.addTo(cal);
    date.setTime(getCalendarTimeInMillis(cal));
}