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:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Creates the General Ledger file given the database data.
 * <p/>//from  w  ww. jav  a 2s  . co m
 * This method does not throw any exception.
 *
 * @param glFileDirectory The directory to create GL file.
 * @param procMessage The process message. Used to build the mail message.
 * @param now The current date.
 * @return true if execution is successful; false otherwise.
 */
private boolean makeGLFile(File glFileDirectory, StringBuilder procMessage, Date now) {
    if (!glFileDirectory.exists() || !glFileDirectory.isDirectory() || !glFileDirectory.canRead()
            || !glFileDirectory.canWrite()) {
        logger.warn("Can not make GL file in directory:" + glFileDirectory);
        procMessage.append(CRLF).append(CRLF).append("Can not make GL file in directory:" + glFileDirectory)
                .append(CRLF);
        return false;
    }

    File outputGLFile = new File(glFileDirectory, "SCGL" + new SimpleDateFormat("yyMMdd").format(now) + ".txt");

    PrintWriter output = null;

    try {
        startTransaction();

        StoredProcedureQuery sp = entityManager.createNamedStoredProcedureQuery("BatchDailyGLFile");
        sp.setParameter("pDayToProcess", now, TemporalType.DATE);
        sp.execute();

        @SuppressWarnings("unchecked")
        List<GLFileRecord> records = sp.getResultList();

        commitTransaction();

        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        String dayOfYear = String.format("%03d", cal.get(Calendar.DAY_OF_YEAR));

        for (GLFileRecord record : records) {
            StringBuilder line = new StringBuilder("");
            line.append(record.getFeederSystemId());
            line.append(record.getJulianDate());
            line.append(dayOfYear);
            line.append(record.getGlFiller());
            line.append(record.getGlCode());

            int fiscalYear = record.getFiscalYear() == null ? 0 : record.getFiscalYear();
            if (fiscalYear < 1000) {
                line.append(StringUtils.rightPad(record.getGlAccountingCode(), 20));
            } else {
                line.append(fiscalYear % 100);
                line.append("  ");
                line.append(StringUtils.rightPad(record.getGlAccountingCode(), 16));
            }

            line.append(String.format("%015d",
                    record.getRecipientAmount().multiply(BatchProcessHelper.HUNDRED).longValue()));

            line.append(record.getRevenueSourceCode());

            // Pad 28 spaces
            for (int i = 0; i < 28; i++) {
                line.append(" ");
            }

            if (output == null) {
                // Lazily create output file only when there is line to write
                output = new PrintWriter(outputGLFile);
            }
            output.println(line.toString());
        }

        if (output != null) {
            output.flush();
            logger.info("General Ledger file created.");
            procMessage.append(CRLF).append(CRLF).append("General Ledger file created.").append(CRLF);
        } else {
            String info = "There are no GL entries for "
                    + DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(now)
                    + " so no GL file was created. ";
            logger.info(info);
            procMessage.append(CRLF).append(CRLF).append(info).append(CRLF);
        }

        return true;
    } catch (PersistenceException pe) {
        logger.error("Database error creating the GL file.", pe);
        procMessage.append(CRLF).append(CRLF).append("Database error creating the GL file.").append(CRLF);
        return false;
    } catch (IOException e) {
        logger.error("IO error creating the GL file.", e);
        procMessage.append(CRLF).append(CRLF).append("IO error creating the GL file.").append(CRLF);
        return false;
    } finally {
        if (output != null) {
            output.close();
        }
    }
}

From source file:org.mifos.accounts.business.AccountBO.java

protected void updateCustomFields(final List<CustomFieldDto> customFields) throws InvalidDateException {
    if (customFields == null) {
        return;/*from w w  w .j  a  va  2  s. co m*/
    }
    for (CustomFieldDto fieldView : customFields) {
        if (fieldView.getFieldType().equals(CustomFieldType.DATE.getValue())
                && org.apache.commons.lang.StringUtils.isNotBlank(fieldView.getFieldValue())) {
            SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                    getUserContext().getPreferredLocale());
            String userfmt = DateUtils.convertToCurrentDateFormat(format.toPattern());
            fieldView.setFieldValue(DateUtils.convertUserToDbFmt(fieldView.getFieldValue(), userfmt));
        }
        if (getAccountCustomFields().size() > 0) {
            for (AccountCustomFieldEntity fieldEntity : getAccountCustomFields()) {
                if (fieldView.getFieldId().equals(fieldEntity.getFieldId())) {
                    fieldEntity.setFieldValue(fieldView.getFieldValue());
                }
            }
        } else {
            for (CustomFieldDto view : customFields) {
                this.getAccountCustomFields()
                        .add(new AccountCustomFieldEntity(this, view.getFieldId(), view.getFieldValue()));
            }
        }
    }
}

From source file:com.miz.functions.MizLib.java

public static String getPrettyDatePrecise(Context context, String date) {
    if (!TextUtils.isEmpty(date)) {
        try {/*from  ww  w  .  j  a  v  a 2  s.c  o  m*/
            String[] dateArray = date.split("-");
            Calendar cal = Calendar.getInstance();
            cal.set(Integer.parseInt(dateArray[0]), Integer.parseInt(dateArray[1]) - 1,
                    Integer.parseInt(dateArray[2]));

            return DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(cal.getTime());
        } catch (Exception e) { // Fall back if something goes wrong
            return date;
        }
    } else {
        return context.getString(R.string.stringNA);
    }
}

From source file:org.exoplatform.outlook.OutlookServiceImpl.java

/**
 * Generate message summary text./*from   w ww  .j  a  va 2s.c  o  m*/
 * 
 * @param message {@link String}
 * @return {@link String}
 */
protected String messageSummary(OutlookMessage message) {
    String fromEmail = message.getFrom().getEmail();
    String fromName = message.getFrom().getDisplayName();
    Date time = message.getCreated().getTime();

    Locale locale = Locale.ENGLISH;
    ResourceBundle res = resourceBundleService.getResourceBundle("locale.outlook.Outlook", locale);

    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
    DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);

    StringBuilder fromLine = new StringBuilder();
    fromLine.append(fromName);
    fromLine.append('<');
    fromLine.append(fromEmail);
    fromLine.append('>');

    StringBuilder summary = new StringBuilder();
    summary.append(res.getString("Outlook.activity.from"));
    summary.append(": <a href='mailto:");
    summary.append(fromEmail);
    summary.append("' target='_top'>");
    summary.append(ContentReader.simpleEscapeHtml(fromLine.toString()));
    summary.append("</a> ");
    summary.append(res.getString("Outlook.activity.on"));
    summary.append(' ');
    summary.append(dateFormat.format(time));
    summary.append(' ');
    summary.append(res.getString("Outlook.activity.at"));
    summary.append(' ');
    summary.append(timeFormat.format(time));

    return summary.toString();
}

From source file:it.fub.jardin.server.DbUtils.java

public User getSimpleUser(Credentials credentials) throws VisibleException {
    String username = credentials.getUsername();
    String password = credentials.getPassword();

    ResultSet result;/*from w ww. j  a  va  2  s .co  m*/

    Connection connection;
    try {
        connection = this.dbConnectionHandler.getConn();
    } catch (HiddenException e) {
        throw new VisibleException(e.getLocalizedMessage());
    }

    String query = "SELECT u.id, u.name, u.surname, u.email, u.office, "
            + "u.telephone, u.status AS userstatus, u.lastlogintime, "
            + "u.logincount, g.id AS groupid, g.name AS groupname " + "FROM " + T_USER + " u JOIN " + T_GROUP
            + " g ON g.id = u.id_group " + "WHERE username = ? and password = PASSWORD(?) AND u.status = '1'";
    // JardinLogger.debug("query getuser:"
    // + "SELECT u.id, u.name, u.surname, u.email, u.office, "
    // + "u.telephone, u.status AS userstatus, u.lastlogintime, "
    // + "u.logincount, g.id AS groupid, g.name AS groupname " + "FROM "
    // + T_USER + " u JOIN " + T_GROUP + " g ON g.id = u.id_group "
    // + "WHERE username = " + username + " and password = PASSWORD("
    // + password + ") AND status = '1'");
    PreparedStatement ps;
    try {
        ps = connection.prepareStatement(query);
        ps.setString(1, username);
        ps.setString(2, password);
    } catch (SQLException e) {
        throw new VisibleException("Errore nella query " + "per la verifica di username e password");
    }

    try {
        result = ps.executeQuery();
    } catch (SQLException e) {
        // Log.debug("User validation query: " + ps.toString());
        e.printStackTrace();
        throw new VisibleException("Errore durante l'interrogazione su database");
    }

    int rows = 0;
    try {
        while (result.next()) {
            rows++;
            if (rows > 1) {
                throw new VisibleException(
                        "Errore nel database degli utenti: " + "due account con username e password uguali");
            }

            // JardinLogger.info("LOGIN: login utente " + credentials.getUsername()
            // + " RIUSCITO!");
            /* Creazione dell'utente con i dati del database */
            int uid = result.getInt("id");
            int gid = result.getInt("groupid");
            String name = result.getString("name");
            String surname = result.getString("surname");
            String group = result.getString("groupname");
            String email = result.getString("email");
            String office = result.getString("office");
            String telephone = result.getString("telephone");
            int status = result.getInt("userstatus");
            int login = result.getInt("logincount");

            DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());
            String last = df.format(new Date());

            /* Carica le preferenze dell'utente */

            List<Message> messages = new ArrayList<Message>();

            User user = new User(uid, gid, new Credentials(username, password), name, surname, group, email,
                    office, telephone, status, login, last);
            this.user = user;

            if (login > 0) {
                login++;
                this.updateLoginCount(uid, login);
                // System.out.println("conto login: " + login);
            }

            return user;
        }
    } catch (Exception e) {
        // Log.warn("Errore SQL", e);
        throw new VisibleException("Errore di accesso " + "al risultato dell'interrogazione su database");
    } finally {
        try {
            this.dbConnectionHandler.closeConn(connection);
        } catch (HiddenException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // JardinLogger.info("Errore LOGIN: tentativo di login utente "
    // + credentials.getUsername() + " FALLITO!");
    throw new VisibleException("Errore di accesso: username o password errati");
}

From source file:net.sf.jasperreports.chartthemes.simple.SimpleChartTheme.java

protected void setAxisTickLabels(Axis axis, JRFont tickLabelFont, Paint tickLabelColor, String tickLabelMask,
        AxisSettings axisSettings) {/*w  w w .  j  av a 2  s . com*/
    boolean axisTickLabelsVisible = axisSettings.getTickLabelsVisible() == null
            || axisSettings.getTickLabelsVisible();//FIXMETHEME axis visibility should be dealt with above;

    axis.setTickLabelsVisible(axisTickLabelsVisible);

    if (axisTickLabelsVisible) {
        JRBaseFont font = new JRBaseFont();
        FontUtil.copyNonNullOwnProperties(axisSettings.getTickLabelFont(), font);
        FontUtil.copyNonNullOwnProperties(tickLabelFont, font);
        font = new JRBaseFont(getChart(), font);
        axis.setTickLabelFont(getFontUtil().getAwtFont(font, getLocale()));

        RectangleInsets tickLabelInsets = axisSettings.getTickLabelInsets();
        if (tickLabelInsets != null) {
            axis.setTickLabelInsets(tickLabelInsets);
        }

        Paint tickLabelPaint = tickLabelColor != null ? tickLabelColor
                : axisSettings.getTickLabelPaint() != null ? axisSettings.getTickLabelPaint().getPaint() : null;

        if (tickLabelPaint != null) {
            axis.setTickLabelPaint(tickLabelPaint);
        }

        TimeZone timeZone = getChartContext().getTimeZone();
        if (axis instanceof DateAxis && timeZone != null) {
            // used when no mask is set
            ((DateAxis) axis).setTimeZone(timeZone);
        }

        if (tickLabelMask != null) {
            if (axis instanceof NumberAxis) {
                NumberFormat fmt = NumberFormat.getInstance(getLocale());
                if (fmt instanceof DecimalFormat)
                    ((DecimalFormat) fmt).applyPattern(tickLabelMask);
                ((NumberAxis) axis).setNumberFormatOverride(fmt);
            } else if (axis instanceof DateAxis) {
                DateFormat fmt;
                if (tickLabelMask.equals("SHORT") || tickLabelMask.equals("DateFormat.SHORT"))
                    fmt = DateFormat.getDateInstance(DateFormat.SHORT, getLocale());
                else if (tickLabelMask.equals("MEDIUM") || tickLabelMask.equals("DateFormat.MEDIUM"))
                    fmt = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale());
                else if (tickLabelMask.equals("LONG") || tickLabelMask.equals("DateFormat.LONG"))
                    fmt = DateFormat.getDateInstance(DateFormat.LONG, getLocale());
                else if (tickLabelMask.equals("FULL") || tickLabelMask.equals("DateFormat.FULL"))
                    fmt = DateFormat.getDateInstance(DateFormat.FULL, getLocale());
                else
                    fmt = new SimpleDateFormat(tickLabelMask, getLocale());

                // FIXME fmt cannot be null
                if (fmt != null) {
                    if (timeZone != null) {
                        fmt.setTimeZone(timeZone);
                    }

                    ((DateAxis) axis).setDateFormatOverride(fmt);
                } else
                    ((DateAxis) axis).setDateFormatOverride(
                            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()));
            }
            // ignore mask for other axis types.
        }
    }
}

From source file:net.sf.jasperreports.chartthemes.spring.GenericChartTheme.java

protected void setAxisTickLabels(Axis axis, JRFont tickLabelFont, Paint tickLabelColor, String tickLabelMask,
        Integer baseFontSize) {//  w  ww.ja  v  a2s  .  c  om
    Boolean defaultAxisTickLabelsVisible = (Boolean) getDefaultValue(defaultAxisPropertiesMap,
            ChartThemesConstants.AXIS_TICK_LABELS_VISIBLE);
    if (defaultAxisTickLabelsVisible != null && defaultAxisTickLabelsVisible) {
        Font themeTickLabelFont = getFont(
                (JRFont) getDefaultValue(defaultAxisPropertiesMap, ChartThemesConstants.AXIS_TICK_LABEL_FONT),
                tickLabelFont, baseFontSize);
        axis.setTickLabelFont(themeTickLabelFont);

        RectangleInsets defaultTickLabelInsets = (RectangleInsets) getDefaultValue(defaultAxisPropertiesMap,
                ChartThemesConstants.AXIS_TICK_LABEL_INSETS);
        if (defaultTickLabelInsets != null) {
            axis.setTickLabelInsets(defaultTickLabelInsets);
        }
        Paint tickLabelPaint = tickLabelColor != null ? tickLabelColor
                : (Paint) getDefaultValue(defaultAxisPropertiesMap, ChartThemesConstants.AXIS_TICK_LABEL_PAINT);
        if (tickLabelPaint != null) {
            axis.setTickLabelPaint(tickLabelPaint);
        }

        TimeZone timeZone = getChartContext().getTimeZone();
        if (axis instanceof DateAxis && timeZone != null) {
            // used when no mask is set
            ((DateAxis) axis).setTimeZone(timeZone);
        }

        if (tickLabelMask != null) {
            if (axis instanceof NumberAxis) {
                NumberFormat fmt = NumberFormat.getInstance(getLocale());
                if (fmt instanceof DecimalFormat)
                    ((DecimalFormat) fmt).applyPattern(tickLabelMask);
                ((NumberAxis) axis).setNumberFormatOverride(fmt);
            } else if (axis instanceof DateAxis) {
                DateFormat fmt;
                if (tickLabelMask.equals("SHORT") || tickLabelMask.equals("DateFormat.SHORT"))
                    fmt = DateFormat.getDateInstance(DateFormat.SHORT, getLocale());
                else if (tickLabelMask.equals("MEDIUM") || tickLabelMask.equals("DateFormat.MEDIUM"))
                    fmt = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale());
                else if (tickLabelMask.equals("LONG") || tickLabelMask.equals("DateFormat.LONG"))
                    fmt = DateFormat.getDateInstance(DateFormat.LONG, getLocale());
                else if (tickLabelMask.equals("FULL") || tickLabelMask.equals("DateFormat.FULL"))
                    fmt = DateFormat.getDateInstance(DateFormat.FULL, getLocale());
                else
                    fmt = new SimpleDateFormat(tickLabelMask, getLocale());

                // FIXME fmt cannot be null
                if (fmt != null) {
                    if (timeZone != null) {
                        fmt.setTimeZone(timeZone);
                    }

                    ((DateAxis) axis).setDateFormatOverride(fmt);
                } else
                    ((DateAxis) axis).setDateFormatOverride(
                            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()));
            }
            // ignore mask for other axis types.
        }
    }
}

From source file:de.innovationgate.wga.server.api.WGA.java

/**
 * Returns an OpenWGA date format//from w w w.j  av a2s . c om
 * @param pattern The date format pattern
 * @param locale A locale to use for locale-dependent date parts. Specify null to let the current WebTML context choose the locale.
 * @throws WGException
 */
public DateFormat getDateFormat(String pattern, Locale locale) throws WGException {

    // Select language for language dependent date formats
    if (locale == null) {
        locale = chooseLocale(locale);
    }

    // Language Fallback(s)

    if (WGUtils.isEmpty(pattern)) {
        return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
    }

    // For default patterns
    String lcPattern = pattern.toLowerCase();
    if (lcPattern.endsWith("date") || lcPattern.endsWith("time")) {
        int patternLength;
        if (lcPattern.startsWith("short")) {
            patternLength = DateFormat.SHORT;
        } else if (lcPattern.startsWith("medium")) {
            patternLength = DateFormat.MEDIUM;
        } else if (lcPattern.startsWith("long")) {
            patternLength = DateFormat.LONG;
        } else {
            patternLength = DateFormat.FULL;
        }

        if (lcPattern.endsWith("datetime")) {
            return new TextualDateFormat(locale,
                    DateFormat.getDateTimeInstance(patternLength, patternLength, locale));
        } else if (lcPattern.endsWith("time")) {
            return new TextualDateFormat(locale, DateFormat.getTimeInstance(patternLength, locale));
        } else {
            return new TextualDateFormat(locale, DateFormat.getDateInstance(patternLength, locale));
        }

    } else if (lcPattern.equals("iso8601")) {
        return new ISO8601DateFormat();
    }

    // For custom patterns
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale);
    dateFormat.setLenient(false);
    return new TextualDateFormat(locale, dateFormat);

}

From source file:com.miz.functions.MizLib.java

public static String getPrettyDate(Context context, long millis) {
    if (millis > 0) {
        try {/*  ww  w. j  av  a  2 s  .  c  o  m*/
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(millis);

            return DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(cal.getTime());
        } catch (Exception e) { // Fall back if something goes wrong
            return String.valueOf(millis);
        }
    } else {
        return context.getString(R.string.stringNA);
    }
}