Example usage for java.text DateFormat getDateInstance

List of usage examples for java.text DateFormat getDateInstance

Introduction

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

Prototype

public static final DateFormat getDateInstance(int style, Locale aLocale) 

Source Link

Document

Gets the date formatter with the given formatting style for the given locale.

Usage

From source file:org.olat.core.util.StringHelper.java

/**
 * //  w w w.  j av  a  2 s  . c o  m
 * @param date
 * @param locale
 * @return Formatted date
 */
public static String formatLocaleDateFull(Date date, Locale locale) {
    if (date == null)
        return "-";
    return DateFormat.getDateInstance(DateFormat.FULL, locale).format(date);
}

From source file:org.mifos.framework.util.helpers.DateUtils.java

public static String getUserLocaleDate(Locale locale, Date databaseDate) {
    // the following line is for 1.1 release and will be removed when date
    // is localized
    locale = internalLocale;/*w  w w .  j  a v a  2  s .c  o  m*/
    SimpleDateFormat shortFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);
    return shortFormat.format(databaseDate);
}

From source file:com.sfs.whichdoctor.dao.ItemDAOImpl.java

/**
 * Used to get a TreeMap of ItemBean details for a specified GUID number.
 *
 * @param guid the guid//from w  w w . ja  v  a  2s .c om
 * @param fullResults the full results
 * @param itemTypeVal the item type value
 * @param groupClassVal the group class value
 * @param object2GUID the object2 guid
 * @param startDate the start date
 * @param endDate the end date
 *
 * @return the tree map< string, item bean>
 *
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
@SuppressWarnings("unchecked")
public final TreeMap<String, ItemBean> load(final int guid, final boolean fullResults, final String itemTypeVal,
        final String groupClassVal, final int object2GUID, final String startDate, final String endDate)
        throws WhichDoctorDaoException {

    TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>();

    String itemType = "Group";
    String groupClass = "Members";
    if (itemTypeVal != null) {
        itemType = itemTypeVal;
    }
    if (groupClass != null) {
        groupClass = groupClassVal;
    }

    if (StringUtils.equalsIgnoreCase(itemType, "Employer")
            || StringUtils.equalsIgnoreCase(itemType, "Employee")) {
        itemType = "Employment";
    }

    java.util.Date dtStartDate = null;
    java.util.Date dtEndDate = null;
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
    try {
        dtStartDate = df.parse(startDate);
    } catch (Exception e) {
        dataLogger.debug("Error parsing start date: " + e.getMessage());
    }
    try {
        dtEndDate = df.parse(endDate);
    } catch (Exception e) {
        dataLogger.debug("Error parsing end date: " + e.getMessage());
    }
    if (dtStartDate != null && dtEndDate != null && dtStartDate.compareTo(dtEndDate) > 0) {
        /* Start date is greater than end date, switch around */
        java.util.Date tempStartDate = dtStartDate;
        dtStartDate = dtEndDate;
        dtEndDate = tempStartDate;
    }

    StringBuffer loadItems = new StringBuffer();
    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(guid);
    parameters.add(itemType);

    loadItems.append(getLoadSQL(groupClass));

    if (StringUtils.equalsIgnoreCase(groupClass, "Employers")) {
        loadItems.append(" AND items.Object2GUID = ? AND itemtype.Class = ?");
    } else {
        loadItems.append(" AND items.Object1GUID = ? AND itemtype.Class = ?");
    }
    if (object2GUID > 0) {
        loadItems.append(" AND items.Object2GUID = ?");
        parameters.add(object2GUID);
    }

    dataLogger.info("Items for GUID: " + guid + " requested");

    Collection<ItemBean> itemCollection = new ArrayList<ItemBean>();
    try {
        itemCollection = this.getJdbcTemplateReader().query(loadItems.toString(), parameters.toArray(),
                new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        return loadItem(rs);
                    }
                });

    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for this search: " + ie.getMessage());
    }

    for (ItemBean item : itemCollection) {
        if (item.display(dtStartDate, dtEndDate)) {
            items.put(item.getOrderIndex(), item);
        }
    }

    return items;
}

From source file:net.dataforte.cohesive.CSVExporter.java

public void writeFile(OutputStream os) throws IOException {
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale("it"));
    PrintWriter pw = new PrintWriter(os);
    if (header) {
        boolean sep = false;
        for (CSVColumn column : columns) {
            if (sep) {
                pw.print(delimiter);//from  ww  w.j a va2  s  . co  m
            } else {
                sep = true;
            }
            if (useQuotes) {
                pw.print(quote);
            }
            pw.print(column.title);
            if (useQuotes) {
                pw.print(quote);
            }
        }
        pw.println();
    }
    for (Object row : data) {
        boolean sep = false;
        for (CSVColumn column : columns) {
            try {
                Object item = PropertyUtils.getProperty(row, column.property);
                if (sep) {
                    pw.print(delimiter);
                } else {
                    sep = true;
                }
                if (useQuotes) {
                    pw.print(quote);
                }
                if ((column.startIndex != null) && (column.endIndex != null)) {
                    item = ((String) item).substring(column.startIndex, column.endIndex);
                } else if (column.startIndex != null) {
                    item = ((String) item).substring(column.startIndex);
                } else if (column.endIndex != null) {
                    item = ((String) item).substring(0, column.endIndex);
                }
                if (column.format != null) {
                    pw.print(column.format.format(new Object[] { item }));
                } else if (item instanceof java.util.Date) {

                    pw.print(df.format((Date) item));
                } else {
                    pw.print(item.toString());
                }
                if (useQuotes) {
                    pw.print(quote);
                }
            } catch (Throwable t) {
                log.error("", t);
            }
        }
        pw.println();
    }
    pw.close();
}

From source file:de.nico.ha_manager.activities.AddHomework.java

private void setTextViewUntil(int[] date) {
    // Format to 31.12.14 or local version of that
    DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    GregorianCalendar gc = new GregorianCalendar(date[0], date[1], date[2]);
    until = f.format(gc.getTime());//  ww  w.  j ava  2 s  . co m

    // Format to Week of Day, for example Mo. or local version of that
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE", Locale.getDefault());
    String asWeek = dateFormat.format(gc.getTime());

    // Tab space because else the date is too far to the left
    until = (asWeek + ", " + until);
    Button untilButton = (Button) findViewById(R.id.button_until);
    untilButton.setText(until);

}

From source file:org.mifos.framework.util.helpers.DateUtils.java

public static String getUserLocaleDate(Locale locale, String databaseDate) {
    // the following line is for 1.1 release and will be removed when date
    // is localized
    locale = internalLocale;// www  .j  a  v a 2 s  . c  o m
    if (locale != null && databaseDate != null && !databaseDate.equals("")) {
        try {
            SimpleDateFormat shortFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                    locale);
            String userfmt = convertToCurrentDateFormat(shortFormat.toPattern());
            return convertDbToUserFmt(databaseDate, userfmt);
        } catch (FrameworkRuntimeException e) {
            throw e;
        } catch (Exception e) {
            System.out.println("databaseDate=" + databaseDate + ", locale=" + locale);
            throw new FrameworkRuntimeException(e);
        }
    } else {
        return "";
    }
}

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 va 2s .  c om
 * <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:jp.furplag.util.time.DateTimeUtils.java

/**
 * create a localized pattern string describing the datetime format from a two character style pattern.
 * <p>//  w  ww. ja v a2 s.c  o  m
 * The first character of {@code style} is the date style, and the second character is the time style.
 * </p>
 *
 * @param style specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be omitted by specifying a style character '-'.
 * @param locale
 * @return
 */
public static String getPattern(final String style, final Object locale) {
    FormatStyle[] styles = FormatStyle.forStyles(style);
    StringBuilder sb = new StringBuilder();
    if (styles[0].is())
        sb.append(((SimpleDateFormat) DateFormat.getDateInstance(styles[0].style,
                Localizer.getAvailableLocale(locale))).toPattern());
    if (styles[0].is() && styles[1].is())
        sb.append(" ");
    if (styles[1].is())
        sb.append(((SimpleDateFormat) DateFormat.getTimeInstance(styles[1].style,
                Localizer.getAvailableLocale(locale))).toPattern());

    return sb.toString();
}

From source file:me.taylorkelly.mywarp.bukkit.commands.printer.InfoPrinter.java

/**
 * Gets information text.//from w w  w.  jav  a 2 s.  c  o  m
 *
 * @param receiver the Actor who will receive the text
 * @return the text
 */
public String getText(Actor receiver) {
    StrBuilder info = new StrBuilder();
    // heading
    info.append(ChatColor.GOLD);
    info.append(MESSAGES.getString("info.heading",
            ChatColor.getByChar(warp.getType().getColorCharacter()) + warp.getName() + ChatColor.GOLD));
    info.appendNewLine();

    // creator
    info.append(ChatColor.GRAY);

    info.append(MESSAGES.getString("info.created-by"));
    info.append(" ");
    info.append(ChatColor.WHITE);
    Profile creator = warp.getCreator();
    info.append(creator.getName().or(creator.getUniqueId().toString()));
    if (receiver instanceof LocalPlayer && warp.isCreator((LocalPlayer) receiver)) {
        info.append(" ");
        info.append(MESSAGES.getString("info.created-by-you"));
    }
    info.appendNewLine();

    // location
    info.append(ChatColor.GRAY);
    info.append(MESSAGES.getString("info.location"));
    info.append(" ");
    info.append(ChatColor.WHITE);
    info.append(MESSAGES.getString("info.location.position", warp.getPosition().getFloorX(),
            warp.getPosition().getFloorY(), warp.getPosition().getFloorZ(), warp.getWorld().getName()));

    info.appendNewLine();

    // if the warp is modifiable, show information about invitations
    if (warp.isModifiable(receiver)) {

        // invited players
        info.append(ChatColor.GRAY);
        info.append(MESSAGES.getString("info.invited-players"));
        info.append(" ");
        info.append(ChatColor.WHITE);

        Set<Profile> invitedPlayers = warp.getInvitedPlayers();
        if (invitedPlayers.isEmpty()) {
            info.append("-");
        } else {
            List<String> invitedPlayerNames = new ArrayList<String>();
            for (Profile profile : invitedPlayers) {
                invitedPlayerNames.add(profile.getName().or(profile.getUniqueId().toString()));
            }
            Collections.sort(invitedPlayerNames);
            info.appendWithSeparators(invitedPlayerNames, ", ");
        }
        info.appendNewLine();

        // invited groups
        info.append(ChatColor.GRAY);
        info.append(MESSAGES.getString("info.invited-groups"));
        info.append(" ");
        info.append(ChatColor.WHITE);

        List<String> invitedGroups = Ordering.natural().sortedCopy(warp.getInvitedGroups());
        if (invitedGroups.isEmpty()) {
            info.append("-");
        } else {
            info.appendWithSeparators(invitedGroups, ", ");
        }
        info.appendNewLine();
    }

    // creation date
    info.append(ChatColor.GRAY);
    info.append(MESSAGES.getString("info.creation-date", warp.getCreationDate()));
    info.append(" ");
    info.append(ChatColor.WHITE);
    info.append(DateFormat.getDateInstance(DateFormat.DEFAULT, LocaleManager.getLocale())
            .format(warp.getCreationDate()));

    info.appendNewLine();

    // visits
    info.append(ChatColor.GRAY);
    info.append(MESSAGES.getString("info.visits"));
    info.append(" ");
    info.append(ChatColor.WHITE);
    info.append(MESSAGES.getString("info.visits.per-day", warp.getVisits(), warp.getVisitsPerDay()));
    return info.toString();
}

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 ww  w  .j  a  va  2 s . co  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;
}