Example usage for java.text DateFormat LONG

List of usage examples for java.text DateFormat LONG

Introduction

In this page you can find the example usage for java.text DateFormat LONG.

Prototype

int LONG

To view the source code for java.text DateFormat LONG.

Click Source Link

Document

Constant for long style pattern.

Usage

From source file:com.distributedapplication.springcontrollers.TestController.java

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String homeTest(Locale locale, Model model) {
    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    //serverTime is a model attribute to passed to the view 
    // it will bounded to the view
    model.addAttribute("serverTime", formattedDate);

    return "home"; //name of .jsp to be invoked
}

From source file:ubic.gemma.model.common.auditAndSecurity.AuditEventValueObject.java

@Override
public String toString() {
    StringBuilder buf = new StringBuilder();
    if (this.getPerformer() == null) {
        buf.append(AuditEventValueObject.TROUBLE_UNKNOWN_NAME);
    } else {//from w w  w. j  a  va 2 s.c  o m
        buf.append(this.getPerformer());
    }

    try {
        buf.append(" on ").append(
                DateFormat.getDateInstance(DateFormat.LONG, Locale.getDefault()).format(this.getDate()));
    } catch (Exception ex) {
        LogFactory.getLog(this.getClass()).error(ex);
    }
    buf.append(": ");

    boolean hasNote = false;

    if (!StringUtils.isEmpty(this.getNote())) {
        buf.append(this.getNote());
        hasNote = true;
    }
    if (!StringUtils.isEmpty(this.getDetail())) {
        if (hasNote) {
            buf.append(" - ");
        }
        buf.append(this.getDetail());
    }
    return buf.toString();
}

From source file:com.concursive.connect.web.modules.calendar.utils.CalendarViewUtils.java

public static CalendarView generateCalendarView(Connection db, CalendarBean calendarInfo, Project project,
        User user, String filter) throws SQLException {

    // Generate a new calendar
    CalendarView calendarView = new CalendarView(calendarInfo, user.getLocale());

    if (calendarInfo.getShowHolidays()) {
        // Add some holidays based on the user locale
        calendarView.addHolidays();/*from  w  ww . j a  va  2s  .  co m*/
    }

    // Set Start and End Dates for the view, use the user's timezone offset
    // (always use Locale.US which matches the URL format)
    String startValue = calendarView.getCalendarStartDate(calendarInfo.getSource());
    LOG.debug(startValue);
    String userStartValue = DateUtils.getUserToServerDateTimeString(calendarInfo.getTimeZone(),
            DateFormat.SHORT, DateFormat.LONG, startValue, Locale.US);
    LOG.debug(userStartValue);
    Timestamp startDate = DatabaseUtils.parseTimestamp(userStartValue);
    startDate.setNanos(0);
    LOG.debug(startDate);

    Timestamp endDate = DatabaseUtils.parseTimestamp(
            DateUtils.getUserToServerDateTimeString(calendarInfo.getTimeZone(), DateFormat.SHORT,
                    DateFormat.LONG, calendarView.getCalendarEndDate(calendarInfo.getSource()), Locale.US));
    endDate.setNanos(0);

    if (ProjectUtils.hasAccess(project.getId(), user, "project-tickets-view")) {
        // Show open and closed tickets
        TicketList ticketList = new TicketList();
        ticketList.setProjectId(project.getId());
        ticketList.setOnlyAssigned(true);
        ticketList.setAlertRangeStart(startDate);
        ticketList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            ticketList.setOnlyOpen(true);
        } else if ("completed".equals(filter)) {
            ticketList.setOnlyClosed(true);
        }

        // Retrieve the tickets that meet the criteria
        ticketList.buildList(db);
        for (Ticket thisTicket : ticketList) {
            if (thisTicket.getEstimatedResolutionDate() != null) {
                String alertDate = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisTicket.getEstimatedResolutionDate());
                calendarView.addEvent(alertDate, CalendarEventList.EVENT_TYPES[11], thisTicket);
            }
        }

        // Retrieve the dates in which a ticket has been resolved
        HashMap<String, Integer> dayEvents = ticketList.queryRecordCount(db, UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.TICKET],
                    dayEvents.get(thisDay));
        }
    }
    if (ProjectUtils.hasAccess(project.getId(), user, "project-plan-view")) {
        // List open and closed Requirements
        RequirementList requirementList = new RequirementList();
        requirementList.setProjectId(project.getId());
        requirementList.setBuildAssignments(false);
        requirementList.setAlertRangeStart(startDate);
        requirementList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            requirementList.setOpenOnly(true);
        } else if ("completed".equals(filter)) {
            requirementList.setClosedOnly(true);
        }

        // Retrieve the requirements that meet the criteria
        requirementList.buildList(db);
        // @todo fix timezone for query counts
        requirementList.buildPlanActivityCounts(db);
        for (Requirement thisRequirement : requirementList) {
            // Display Milestone startDate
            if (thisRequirement.getStartDate() != null) {
                String start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisRequirement.getStartDate());
                calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[16], thisRequirement);
            }
            // Display Milestone endDate
            if (thisRequirement.getDeadline() != null) {
                String end = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisRequirement.getDeadline());
                calendarView.addEvent(end, CalendarEventList.EVENT_TYPES[17], thisRequirement);
            }
        }

        // Retrieve the dates in which a requirement has a start or end date
        HashMap<String, HashMap<String, Integer>> dayGroups = requirementList.queryRecordCount(db,
                UserUtils.getUserTimeZone(user));
        for (String type : dayGroups.keySet()) {
            if ("startdate".equals(type)) {
                HashMap<String, Integer> dayEvents = dayGroups.get(type);
                for (String thisDay : dayEvents.keySet()) {
                    calendarView.addEventCount(thisDay,
                            CalendarEventList.EVENT_TYPES[CalendarEventList.MILESTONE_START],
                            dayEvents.get(thisDay));
                }
            } else if ("enddate".equals(type)) {
                HashMap<String, Integer> dayEvents = dayGroups.get(type);
                for (String thisDay : dayEvents.keySet()) {
                    calendarView.addEventCount(thisDay,
                            CalendarEventList.EVENT_TYPES[CalendarEventList.MILESTONE_END],
                            dayEvents.get(thisDay));
                }
            }

        }

        // Retrieve assignments that meet the criteria
        AssignmentList assignmentList = new AssignmentList();
        assignmentList.setProjectId(project.getId());
        assignmentList.setOnlyIfRequirementOpen(true);
        assignmentList.setAlertRangeStart(startDate);
        assignmentList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            assignmentList.setIncompleteOnly(true);
        } else if ("completed".equals(filter)) {
            assignmentList.setClosedOnly(true);
        }

        // Display the user's assignments by due date
        assignmentList.buildList(db);
        for (Assignment thisAssignment : assignmentList) {
            if (thisAssignment.getDueDate() != null) {
                String dueDate = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisAssignment.getDueDate());
                calendarView.addEvent(dueDate, CalendarEventList.EVENT_TYPES[8], thisAssignment);
            }
        }

        // Retrieve the dates in which an assignment has a due date
        HashMap<String, Integer> dayEvents = assignmentList.queryAssignmentRecordCount(db,
                UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.ASSIGNMENT],
                    dayEvents.get(thisDay));
        }
    }

    if (ProjectUtils.hasAccess(project.getId(), user, "project-calendar-view")) {
        MeetingList meetingList = new MeetingList();
        meetingList.setProjectId(project.getId());
        meetingList.setEventSpanStart(startDate);
        if (!calendarInfo.isAgendaView()) {
            // limit the events to the date range chosen
            meetingList.setEventSpanEnd(endDate);
        }
        meetingList.setBuildAttendees(true);
        meetingList.buildList(db);
        LOG.debug("Meeting count = " + meetingList.size());
        // Display the meetings by date
        for (Meeting thisMeeting : meetingList) {
            if (thisMeeting.getStartDate() != null) {
                String start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisMeeting.getStartDate());
                if ("pending".equals(filter)) {
                    if (thisMeeting.getStartDate().getTime() > System.currentTimeMillis()) {
                        calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                                thisMeeting);
                    }
                } else if ("completed".equals(filter)) {
                    if (thisMeeting.getEndDate().getTime() < System.currentTimeMillis()) {
                        calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                                thisMeeting);
                    }
                } else {
                    if (calendarInfo.isAgendaView()) {
                        // Display meetings that started before today, but last greater than today, on the startDate of the calendar display
                        if (thisMeeting.getStartDate().before(startDate)) {
                            start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                                    DateFormat.SHORT, startDate);
                        }
                    }
                    calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                            thisMeeting);
                }
                LOG.debug("Meeting added for date: " + start);
            }
        }

        // Retrieve the dates for meeting events
        HashMap<String, Integer> dayEvents = meetingList.queryRecordCount(db, UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            LOG.debug("addingCount: " + thisDay + " = " + dayEvents.get(thisDay));
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                    dayEvents.get(thisDay));
        }
    }
    return calendarView;
}

From source file:de.uniwue.info6.webapp.admin.SubmissionRow.java

public String getEntryDate() {
    if (userEntry != null) {
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL,
                new Locale("de", "DE"));
        return df.format(userEntry.getEntryTime());
    }/*from w ww  .  j a  v a  2  s  . c  o m*/
    return "---";
}

From source file:org.occupycincy.android.OccupyCincyActivity.java

private void processFeed() {

    feedItems = new ArrayList<HashMap<String, String>>();

    // default to Never
    String lastUpdated = getString(R.string.last_updated_never);

    File file = new File(getFullPath(getString(R.string.occupy_feed_file)));
    if (file.exists()) {
        parseOccupyFeed();/* w w  w  .  ja  v  a  2  s  . c o m*/
        lastUpdated = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT)
                .format(new Date(file.lastModified()));
    }

    populateBlogView();

    // display Last Updated: 
    TextView txtLastUpdated = (TextView) findViewById(R.id.txtLastUpdated);
    txtLastUpdated.setText(getString(R.string.last_updated).replace("%TIME%", lastUpdated));

    setLoading(false);
}

From source file:ilearn.orb.controller.AnalysisController.java

private static UserProfile retrieveProfile(HttpSession session, int userId)
        throws NumberFormatException, Exception {
    UserProfile p = null;/*from ww  w.  j ava 2 s  .  co m*/
    User[] students = null;
    User selectedStudent = null;
    if (userId < 0) {
        students = HardcodedUsers.defaultStudents();
        selectedStudent = selectedStudent(students, userId);
        //p = HardcodedUsers.defaultProfile(selectedStudent.getId());
        String json = UserServices
                .getDefaultProfile(HardcodedUsers.defaultProfileLanguage(selectedStudent.getId()));
        if (json != null)
            p = new Gson().fromJson(json, UserProfile.class);

    } else {
        Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer())
                .setDateFormat(DateFormat.LONG).create();
        String json = UserServices.getProfiles(Integer.parseInt(session.getAttribute("id").toString()),
                session.getAttribute("auth").toString());
        students = gson.fromJson(json, User[].class);
        selectedStudent = selectedStudent(students, userId);

        json = UserServices.getJsonProfile(userId, session.getAttribute("auth").toString());
        if (json != null)
            p = new Gson().fromJson(json, UserProfile.class);
    }
    return p;
}

From source file:org.sakaiproject.tool.accountinfo.rsf.AccountInfoProducer.java

public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    User user = userDirectoryService.getCurrentUser();
    String username = user.getDisplayName();
    Session session = sessionManager.getCurrentSession();
    UCTLDAPUser uctUser = null;//from ww  w .  j av a 2s  .c om
    if (session.getAttribute("ldapUser") == null) {
        uctUser = new UCTLDAPUser(user);
        session.setAttribute("ldapUser", uctUser);
    } else {
        uctUser = (UCTLDAPUser) session.getAttribute("ldapUser");
        long cache = new Date().getTime();
        if (uctUser.getCacheTime().before(new Date(cache - CACHETTL))) {
            uctUser = new UCTLDAPUser(user);
            session.setAttribute("ldapUser", uctUser);
        }
    }

    UIOutput.make(tofill, "current-username", username);

    Date passExp = uctUser.getAccountExpiry();
    m_log.info("Acc Expiry: " + passExp + "(" + user + ")");
    if (passExp != null) {

        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, localegetter.get());
        UIOutput.make(tofill, "passEx");
        UIOutput.make(tofill, "ldap-pass-expires", passExp.toString());
        m_log.debug(user + ": " + uctUser.getAccountIsExpired());
        if (uctUser.getAccountIsExpired() == true) {
            UIOutput.make(tofill, "ldap-password-good", messageLocator.getMessage("passwd_exp_msg"));
            Object[] rep = new Object[] { (Object) uctUser.getGraceLoginsTotal(),
                    (Object) uctUser.getGraceLoginsRemaining() };

            UIOutput.make(tofill, "ldap-gracelogins-remaining",
                    messageLocator.getMessage("grace_logins_label", rep));
        }

    }

    Date dob = uctUser.getDOB();
    if (dob != null) {
        DateFormat monthday = new SimpleDateFormat("MMMMdd");
        String dobStr = monthday.format(dob);
        String todayStr = monthday.format(new Date());

        if (dob != null && dobStr.equals(todayStr)) {
            m_log.info("its this users Birthday!");
            UIOutput.make(tofill, "bday");
        }
    }

    UILink pLink = UILink.make(tofill, "password_link", messageLocator.getMessage("pwd_selfs_text"),
            messageLocator.getMessage("pwd_selfs_url"));
    // pLink.decorators = new DecoratorList(new
    // UITargetDecorator("_blank"));

    if (user.getType().equals("student") || user.getType().equals("staff"))
        UIOutput.make(tofill, "seperator");

    if (user.getType().equals("student")) {

        UILink psLink = UILink.make(tofill, "ps_login", messageLocator.getMessage("ps_link_text"),
                messageLocator.getMessage("ps_student_link"));

    } else if (user.getType().equals("staff")) {
        UILink.make(tofill, "ps_login", messageLocator.getMessage("ps_link_text"),
                messageLocator.getMessage("ps_staff_link"));
    }

}

From source file:lucee.commons.i18n.FormatUtil.java

public static DateFormat[] getTimeFormats(Locale locale, TimeZone tz, boolean lenient) {
    String id = "t-" + locale.hashCode() + "-" + tz.getID() + "-" + lenient;
    DateFormat[] df = formats.get(id);
    if (df == null) {
        List<DateFormat> list = new ArrayList<DateFormat>();
        list.add(DateFormat.getTimeInstance(DateFormat.FULL, locale));
        list.add(DateFormat.getTimeInstance(DateFormat.LONG, locale));
        list.add(DateFormat.getTimeInstance(DateFormat.MEDIUM, locale));
        list.add(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
        add24(list, locale);/*from  w  w w  .  ja  va  2s  . com*/
        addCustom(list, locale, FORMAT_TYPE_TIME);
        df = list.toArray(new DateFormat[list.size()]);

        for (int i = 0; i < df.length; i++) {
            df[i].setLenient(lenient);
            df[i].setTimeZone(tz);
        }
        formats.put(id, df);
    }
    return df;
}

From source file:org.nuxeo.ecm.platform.ui.web.component.seam.UICellExcel.java

/**
 * Converts string value as returned by widget to the target type for an accurate cell format in the XLS/CSV export.
 * <ul>/*from w w  w. j a v a  2  s.  c o  m*/
 * <li>If force type is set to "number", convert value to a double (null if empty).</li>
 * <li>If force type is set to "bool", convert value to a boolean (null if empty).</li>
 * <li>If force type is set to "date", convert value to a date using most frequent date parsers using the short,
 * medium, long and full formats and current locale, trying first with time information and after with only date
 * information. Returns null if date is empty or could not be parsed.</li>
 * </ul>
 *
 * @since 5.6
 */
protected Object convertStringToTargetType(String value, String forceType) {
    if (CellType.number.name().equals(forceType)) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return Double.valueOf(value);
    } else if (CellType.date.name().equals(forceType)) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
        int[] formats = { DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL };
        for (int format : formats) {
            try {
                return DateFormat.getDateTimeInstance(format, format, locale).parse(value);
            } catch (ParseException e) {
                // ignore
            }
            try {
                return DateFormat.getDateInstance(format, locale).parse(value);
            } catch (ParseException e) {
                // ignore
            }
        }
        log.warn("Could not convert value to a date instance: " + value);
        return null;
    } else if (CellType.bool.name().equals(forceType)) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return Boolean.valueOf(value);
    }
    return value;
}

From source file:org.openmrs.web.taglib.FormatDateTag.java

public int doStartTag() {
    RequestContext requestContext = (RequestContext) this.pageContext
            .getAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE);

    if (date == null && getPath() != null) {
        try {//from  w  w  w. j  a  v a 2  s . c  o m
            // get the "path" object from the pageContext
            String resolvedPath = getPath();
            String nestedPath = (String) pageContext.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME,
                    PageContext.REQUEST_SCOPE);
            if (nestedPath != null) {
                resolvedPath = nestedPath + resolvedPath;
            }

            BindStatus status = new BindStatus(requestContext, resolvedPath, false);
            log.debug("status: " + status);

            if (status.getValue() != null) {
                log.debug("status.value: " + status.getValue());
                if (status.getValue().getClass() == Date.class) {
                    // if no editor was registered all will go well here
                    date = (Date) status.getValue();
                } else {
                    // if a "Date" property editor was registerd for the form, the status.getValue()
                    // object will be a java.lang.String.  This is useless.  Try getting the original
                    // value from the troublesome editor
                    log.debug("status.valueType: " + status.getValueType());
                    Timestamp timestamp = (Timestamp) status.getEditor().getValue();
                    date = new Date(timestamp.getTime());
                }
            }
        } catch (Exception e) {
            log.warn("Unable to get a date object from path: " + getPath(), e);
            return SKIP_BODY;
        }
    }

    if (!dateWasSet && date == null) {
        log.warn("Both 'date' and 'path' cannot be null.  Page: " + pageContext.getPage() + " localname:"
                + pageContext.getRequest().getLocalName() + " rd:"
                + pageContext.getRequest().getRequestDispatcher(""));
        return SKIP_BODY;
    }

    if (type == null) {
        type = "";
    }

    DateFormat dateFormat = null;

    if (format != null && format.length() > 0) {
        dateFormat = new SimpleDateFormat(format, Context.getLocale());
    } else if (type.equals("xml")) {
        dateFormat = new SimpleDateFormat("dd-MMM-yyyy", Context.getLocale());
    } else {
        log.debug("context locale: " + Context.getLocale());

        if (type.equals("long")) {
            dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Context.getLocale());
        } else if (type.equals("medium")) {
            dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Context.getLocale());
        } else {
            dateFormat = Context.getDateFormat();
        }
    }

    if (dateFormat == null) {
        dateFormat = new SimpleDateFormat("MM-dd-yyyy");
    }

    String datestr = "";

    try {
        if (date != null) {
            if (type.equals("milliseconds")) {
                datestr = "" + date.getTime();
            } else {
                if (showTodayOrYesterday && (DateUtils.isSameDay(Calendar.getInstance().getTime(), date)
                        || OpenmrsUtil.isYesterday(date))) {
                    //print only time of day but maintaining the format(24 Vs 12) if any was specified
                    String timeFormatString = (format != null && !format.contains("a")) ? "HH:mm" : "h:mm a";
                    dateFormat = new SimpleDateFormat(timeFormatString);
                    if (DateUtils.isSameDay(Calendar.getInstance().getTime(), date)) {
                        datestr = Context.getMessageSourceService().getMessage("general.today") + " "
                                + dateFormat.format(date);
                    } else {
                        datestr = Context.getMessageSourceService().getMessage("general.yesterday") + " "
                                + dateFormat.format(date);
                    }
                } else {
                    datestr = dateFormat.format(date);
                }
            }
        }
    } catch (IllegalArgumentException e) {
        //format or date is invalid
        log.error("date: " + date);
        log.error("format: " + format);
        log.error(e);
        datestr = date.toString();
    }

    try {
        pageContext.getOut().write(datestr);
    } catch (IOException e) {
        log.error(e);
    }

    // reset the objects to null because taglibs are reused
    release();

    return SKIP_BODY;
}