Example usage for java.util Calendar MILLISECOND

List of usage examples for java.util Calendar MILLISECOND

Introduction

In this page you can find the example usage for java.util Calendar MILLISECOND.

Prototype

int MILLISECOND

To view the source code for java.util Calendar MILLISECOND.

Click Source Link

Document

Field number for get and set indicating the millisecond within the second.

Usage

From source file:com.ocs.dynamo.utils.DateUtils.java

/**
 * Truncates a calendar object, setting all time fields to zero
 * /*from ww w .j  a  v a 2s. c o  m*/
 * @param calendar
 * @return
 */
public static Calendar truncate(Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar;
}

From source file:Main.java

/**
 * Returns the number of milliseconds within the 
 * fragment. All datefields greater than the fragment will be ignored. 
 * //from w w w .java 2s .  c om
 * Asking the milliseconds of any date will only return the number of milliseconds
 * of the current second (resulting in a number between 0 and 999). This 
 * method will retrieve the number of milliseconds for any fragment. 
 * For example, if you want to calculate the number of seconds past today, 
 * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will
 * be all seconds of the past hour(s), minutes(s) and second(s). 
 * 
 * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both 
 * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, 
 * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
 * A fragment less than or equal to a MILLISECOND field will return 0. 
 * 
 * 
 * <ul>
 *  <li>January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
 *   (equivalent to calendar.get(Calendar.MILLISECOND))</li>
 *  <li>January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
 *   (equivalent to calendar.get(Calendar.MILLISECOND))</li>
 *  <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538
 *   (10*1000 + 538)</li>
 *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
 *   (a millisecond cannot be split in milliseconds)</li>
 * </ul>
 * 
 * 
 * @param calendar the calendar to work with, not null
 * @param fragment the Calendar field part of calendar to calculate 
 * @return number of milliseconds within the fragment of date
 * @throws IllegalArgumentException if the date is <code>null</code> or 
 * fragment is not supported
 * @since 2.4
 */
public static long getFragmentInMilliseconds(Calendar calendar, int fragment) {
    return getFragment(calendar, fragment, Calendar.MILLISECOND);
}

From source file:DateUtil.java

/**
 * Returns a Date set to the first possible millisecond of the minute.
 * If a null day is passed in, a new Date is created.
 *//*from  w w w.j a  va 2 s .  c o  m*/
public static Date getStartOfMinute(Date day, Calendar cal) {
    if (day == null)
        day = new Date();
    cal.setTime(day);
    cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
    cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
    return cal.getTime();
}

From source file:com.email.SendEmailCalInvite.java

/**
 * Builds the calendar invite for the email
 *
 * @param eml EmailOutInvitesModel//from  ww w. j a  v  a 2  s  .co m
 * @return BodyPart (calendar invite)
 */
private static BodyPart inviteCalObject(EmailOutInvitesModel eml, SystemEmailModel account,
        String emailSubject) {
    BodyPart calendarPart = new MimeBodyPart();
    try {
        String calendarContent = "BEGIN:VCALENDAR\n" + "METHOD:REQUEST\n" + "PRODID: BCP - Meeting\n"
                + "VERSION:2.0\n" + "BEGIN:VEVENT\n" + "DTSTAMP:"
                + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTSTART:"
                + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTEND:"
                + Global.getiCalendarDateFormat().format(eml.getHearingEndTime()) + "\n"
                //Subject
                + "SUMMARY:" + emailSubject.replace("Upcoming", "").trim() + "\n" + "UID:"
                + Calendar.getInstance().get(Calendar.MILLISECOND) + "\n"
                //return email
                + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"
                + new InternetAddress(account.getEmailAddress()).getAddress() + "\n"
                //return email
                + "ORGANIZER:MAILTO:" + new InternetAddress(account.getEmailAddress()).getAddress() + "\n"
                //hearing room
                + "LOCATION: " + eml.getHearingRoomAbv() + "\n"
                //subject
                + "DESCRIPTION: " + emailSubject + "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n"
                + "STATUS:CONFIRMED\n" + "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n"
                + "DESCRIPTION:REMINDER\n" + "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n"
                + "END:VEVENT\n" + "END:VCALENDAR";
        calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
        calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");
    } catch (MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
    return calendarPart;
}

From source file:at.medevit.elexis.ehc.core.internal.EhcCoreServiceTest.java

@Test
public void testGetPatientDocument() {
    EhcCoreServiceImpl service = new EhcCoreServiceImpl();
    CdaCh cda = service.getCdaChDocument(patient, mandant);
    assertNotNull(cda);// w  w w  . j av a 2  s  .c o m
    org.ehealth_connector.common.Patient cdaPatient = cda.getPatient();
    assertNotNull(cdaPatient);
    assertEquals("name", cdaPatient.getName().getFamilyName());
    assertEquals("firstname", cdaPatient.getName().getGivenNames());
    assertEquals(AdministrativeGender.FEMALE, cdaPatient.getAdministrativeGenderCode());
    Calendar bDay = Calendar.getInstance();
    bDay.set(2000, 00, 01, 00, 00, 00);
    bDay.set(Calendar.MILLISECOND, 00);
    assertEquals(bDay.getTime(), cdaPatient.getBirthday());
    List<Address> addresses = cdaPatient.getAddresses();
    assertFalse(addresses.isEmpty());
    assertEquals("City", addresses.get(0).getCity());

    HashMap<String, AddressUse> phones = cdaPatient.getTelecoms().getPhones();
    assertFalse(phones.isEmpty());
    assertTrue(phones.containsKey("tel:+01555123"));
}

From source file:org.kuali.mobility.sakai.service.SakaiSiteServiceImpl.java

@SuppressWarnings("unchecked")
public Home findSakaiHome(String user, String shortDate) {
    try {/* w w  w  .java  2s.c o  m*/
        String url = configParamService.findValueByName("Sakai.Url.Base") + "user_prefs.json";
        ResponseEntity<InputStream> is = oncourseOAuthService.oAuthGetRequest(user, url, "text/html");
        String prefsJson = IOUtils.toString(is.getBody(), "UTF-8");
        Set<String> visibleSiteIds = new HashSet<String>();
        try {
            JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(prefsJson);
            JSONArray itemArray = jsonObj.getJSONArray("user_prefs_collection");
            if (itemArray != null) {
                for (Iterator<JSONObject> iter = itemArray.iterator(); iter.hasNext();) {
                    JSONObject object = iter.next();
                    visibleSiteIds.add(object.getString("siteId"));
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        Set<String> calendarCourseIds = new HashSet<String>();
        try {
            Calendar todayDate = Calendar.getInstance();
            Calendar tomorrowDate = Calendar.getInstance();
            if (shortDate != null) {
                try {
                    todayDate.setTime(Constants.DateFormat.queryStringDateFormat.getFormat().parse(shortDate));
                } catch (Exception e) {
                }
            }
            todayDate.set(Calendar.HOUR, 0);
            todayDate.set(Calendar.MINUTE, 0);
            todayDate.set(Calendar.SECOND, 0);
            todayDate.set(Calendar.MILLISECOND, 0);
            tomorrowDate.setTime(todayDate.getTime());
            tomorrowDate.add(Calendar.DATE, 1);
            ListViewEvents listViewEvents = calendarEventOAuthService.retrieveViewEventsList(user,
                    todayDate.getTime(), todayDate.getTime(), todayDate.getTime(), null);
            List<ListData> events = listViewEvents.getEvents();
            if (events.size() > 0) {
                ListData list = events.get(0);
                List<CalendarViewEvent> viewEvents = list.getEvents();
                for (CalendarViewEvent event : viewEvents) {
                    if (event.getOncourseSiteId() != null) {
                        calendarCourseIds.add(event.getOncourseSiteId().toLowerCase());
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        url = configParamService.findValueByName("Sakai.Url.Base") + "site.json";
        is = oncourseOAuthService.oAuthGetRequest(user, url, "text/html");
        String siteJson = IOUtils.toString(is.getBody(), "UTF-8");

        Home home = new Home();
        List<Term> courses = home.getCourses();
        List<Site> projects = home.getProjects();
        List<Site> other = home.getOther();
        List<Site> today = home.getTodaysCourses();
        Map<String, Term> courseMap = new HashMap<String, Term>();
        Map<String, Site> courseSiteMap = new HashMap<String, Site>();
        List<String> courseSiteIdList = new ArrayList<String>();
        JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(siteJson);
        JSONArray itemArray = jsonObj.getJSONArray("site_collection");
        for (Iterator<JSONObject> iter = itemArray.iterator(); iter.hasNext();) {
            JSONObject object = iter.next();

            String id = object.getString("id");
            if (!visibleSiteIds.contains(id)) {
                continue;
            }

            Site item = new Site();
            item.setId(id);
            item.setTitle(object.getString("title"));
            item.setDescription(object.getString("shortDescription").replace("&nbsp;", " "));

            String type = object.getString("type");
            if ("course".equals(type)) {
                Object jsonProps = object.get("props");
                String term = null;
                if (jsonProps instanceof JSONObject) {
                    JSONObject props = (JSONObject) jsonProps;
                    try {
                        term = props.getString("term");
                        term = term.toLowerCase();
                        String[] split = term.split(" ");
                        term = "";
                        for (String s : split) {
                            s = s.substring(0, 1).toUpperCase() + s.substring(1);
                            term = term + s + " ";
                        }
                        term.trim();
                    } catch (Exception e) {
                    }
                }
                item.setTerm(term);

                Term termObj = courseMap.get(term);
                if (termObj == null) {
                    termObj = new Term();
                    termObj.setTerm(term);
                    courseMap.put(term, termObj);
                }
                termObj.getCourses().add(item);

                courseSiteMap.put(item.getId(), item);
                courseSiteIdList.add(item.getId());

                if (calendarCourseIds.contains(item.getId().toLowerCase())) {
                    today.add(item);
                }
            } else if ("project".equals(type)) {
                projects.add(item);
            } else {
                other.add(item);
            }
        }

        //            try {
        //            List<ViewDetailedEvent> listViewEvents = calendarEventOAuthService.retrieveCourseEvents(user, courseSiteIdList);
        //            for (ViewDetailedEvent event : listViewEvents) {
        //               Site site = courseSiteMap.get(event.getOncourseSiteId());
        //               if (event.getRecurrenceMessage() != null && !event.getRecurrenceMessage().isEmpty()) {
        //                  site.setMeetingTime(event.getRecurrenceMessage());
        //               } else {
        //                  site.setMeetingTime(event.getDisplayDate());
        //               }
        //               site.setLocation(event.getLocation());
        //               site.setBuildingCode(event.getLocationId());
        //            }
        //         } catch (Exception e) {
        //            LOG.error(e.getMessage(), e);
        //         }

        for (Map.Entry<String, Term> entry : courseMap.entrySet()) {
            courses.add(entry.getValue());
        }
        Collections.sort(courses);
        Collections.reverse(courses);
        return home;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return new Home();
    }
}

From source file:net.sourceforge.eclipsetrader.opentick.HistoryFeed.java

public void requestHistoryStream(final Security security, long timeout) {
    Calendar from = Calendar.getInstance();
    Calendar to = Calendar.getInstance();

    to.set(Calendar.HOUR, 23);/*from  www  .  j  av a2  s  .c o m*/
    to.set(Calendar.MINUTE, 59);
    to.set(Calendar.SECOND, 59);
    to.set(Calendar.MILLISECOND, 0);

    HistoryClientAdapter adapter = new HistoryClientAdapter(security);
    client.addListener(adapter);

    String symbol = security.getHistoryFeed().getSymbol();
    if (symbol == null || symbol.length() == 0)
        symbol = security.getCode();
    String exchange = security.getHistoryFeed().getExchange();
    if (exchange == null || exchange.length() == 0)
        exchange = "Q";

    History history = security.getHistory();
    if (history.size() == 0) {
        from = Calendar.getInstance();
        from.add(Calendar.YEAR,
                -CorePlugin.getDefault().getPreferenceStore().getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
    } else {
        Bar last = history.getLast();
        from.setTime(last.getDate());
        from.add(Calendar.DATE, 1);
    }

    from.set(Calendar.HOUR, 0);
    from.set(Calendar.MINUTE, 0);
    from.set(Calendar.SECOND, 0);
    from.set(Calendar.MILLISECOND, 0);

    try {
        adapter.historyStream = client.requestHistData(new OTDataEntity(exchange, symbol),
                (int) (from.getTimeInMillis() / 1000), (int) (to.getTimeInMillis() / 1000),
                OTConstants.OT_HIST_OHLC_DAILY, 1);
        log.debug(String.valueOf(adapter.historyStream) + " / Request History " + security + " ["
                + CorePlugin.getDateFormat().format(from.getTime()) + "-"
                + CorePlugin.getDateFormat().format(to.getTime()) + "]");
    } catch (Exception e) {
        log.warn(e);
    }

    List splits = security.getSplits();
    if (splits.size() == 0) {
        from = Calendar.getInstance();
        from.add(Calendar.YEAR,
                -CorePlugin.getDefault().getPreferenceStore().getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
    } else {
        Split last = (Split) splits.get(splits.size() - 1);
        from.setTime(last.getDate());
        from.add(Calendar.DATE, 1);
    }

    from.set(Calendar.HOUR, 0);
    from.set(Calendar.MINUTE, 0);
    from.set(Calendar.SECOND, 0);
    from.set(Calendar.MILLISECOND, 0);

    try {
        adapter.splitsStream = client.requestSplits(new OTDataEntity(exchange, symbol),
                (int) (from.getTimeInMillis() / 1000), (int) (to.getTimeInMillis() / 1000));
        log.debug(String.valueOf(adapter.splitsStream) + " / Request Splits " + security + " ["
                + CorePlugin.getDateFormat().format(from.getTime()) + "-"
                + CorePlugin.getDateFormat().format(to.getTime()) + "]");
    } catch (Exception e) {
        log.warn(e);
    }

    List dividends = security.getDividends();
    if (dividends.size() == 0) {
        from = Calendar.getInstance();
        from.add(Calendar.YEAR,
                -CorePlugin.getDefault().getPreferenceStore().getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
    } else {
        Dividend last = (Dividend) dividends.get(dividends.size() - 1);
        from.setTime(last.getDate());
        from.add(Calendar.DATE, 1);
    }

    from.set(Calendar.HOUR, 0);
    from.set(Calendar.MINUTE, 0);
    from.set(Calendar.SECOND, 0);
    from.set(Calendar.MILLISECOND, 0);

    try {
        adapter.dividendsStream = client.requestDividends(new OTDataEntity(exchange, symbol),
                (int) (from.getTimeInMillis() / 1000), (int) (to.getTimeInMillis() / 1000));
        log.debug(String.valueOf(adapter.dividendsStream) + " / Request Dividends " + security + " ["
                + CorePlugin.getDateFormat().format(from.getTime()) + "-"
                + CorePlugin.getDateFormat().format(to.getTime()) + "]");
    } catch (Exception e) {
        log.warn(e);
    }

    adapter.started = System.currentTimeMillis();
    try {

        while ((System.currentTimeMillis() - adapter.started) < timeout && !adapter.isCompleted())
            Thread.sleep(100);
    } catch (Exception e) {
        log.warn(e);
    }

    client.removeListener(adapter);

    Collections.sort(security.getDividends(), new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Dividend) o1).getDate().compareTo(((Dividend) o2).getDate());
        }
    });
    Collections.sort(security.getSplits(), new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Split) o1).getDate().compareTo(((Split) o2).getDate());
        }
    });

    CorePlugin.getRepository().save(history);
    CorePlugin.getRepository().save(security);
}

From source file:org.openmrs.module.patientportaltoolkit.api.db.hibernate.HibernateReminderDAO.java

public static Date clearDate(Date dateTime) {
    if (dateTime == null) {
        return null;
    }//from w  w  w.j av a 2 s .c  o  m
    Calendar cal = Calendar.getInstance();
    cal.setTime(dateTime);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date dateWithoutTime = cal.getTime();

    return dateWithoutTime;
}

From source file:com.linuxbox.enkive.statistics.gathering.past.PastGatherer.java

public void consolidatePastWeeks() {
    Calendar c = Calendar.getInstance();
    c.setTime(statDate);/*from   ww w  .  j a v  a 2 s.c  om*/
    c.set(Calendar.MILLISECOND, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.HOUR_OF_DAY, 0);
    while (c.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
        c.add(Calendar.DATE, -1);
    }
    setEndDate(CONSOLIDATION_WEEK);
    if (c.getTimeInMillis() > endDate.getTime()) {
        client.storeData(consolidatePast(CONSOLIDATION_WEEK, c));
    }
}

From source file:com.philliphsu.clock2.alarms.Alarm.java

public long ringsAt() {
    // Always with respect to the current date and time
    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.HOUR_OF_DAY, hour());
    calendar.set(Calendar.MINUTE, minutes());
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    long baseRingTime = calendar.getTimeInMillis();

    if (!hasRecurrence()) {
        if (baseRingTime <= System.currentTimeMillis()) {
            // The specified time has passed for today
            baseRingTime += TimeUnit.DAYS.toMillis(1);
        }//from  w  w  w  .  ja  va2 s .  c  om
        return baseRingTime;
    } else {
        // Compute the ring time just for the next closest recurring day.
        // Remember that day constants defined in the Calendar class are
        // not zero-based like ours, so we have to compensate with an offset
        // of magnitude one, with the appropriate sign based on the situation.
        int weekdayToday = calendar.get(Calendar.DAY_OF_WEEK);
        int numDaysFromToday = -1;

        for (int i = weekdayToday; i <= Calendar.SATURDAY; i++) {
            if (isRecurring(i - 1 /*match up with our day constant*/)) {
                if (i == weekdayToday) {
                    if (baseRingTime > System.currentTimeMillis()) {
                        // The normal ring time has not passed yet
                        numDaysFromToday = 0;
                        break;
                    }
                } else {
                    numDaysFromToday = i - weekdayToday;
                    break;
                }
            }
        }

        // Not computed yet
        if (numDaysFromToday < 0) {
            for (int i = Calendar.SUNDAY; i < weekdayToday; i++) {
                if (isRecurring(i - 1 /*match up with our day constant*/)) {
                    numDaysFromToday = Calendar.SATURDAY - weekdayToday + i;
                    break;
                }
            }
        }

        // Still not computed yet. The only recurring day is weekdayToday,
        // and its normal ring time has already passed.
        if (numDaysFromToday < 0 && isRecurring(weekdayToday - 1)
                && baseRingTime <= System.currentTimeMillis()) {
            numDaysFromToday = 7;
        }

        if (numDaysFromToday < 0)
            throw new IllegalStateException("How did we get here?");

        return baseRingTime + TimeUnit.DAYS.toMillis(numDaysFromToday);
    }
}