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) 

Source Link

Document

Gets the date formatter with the given formatting style for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:de.tobiasbielefeld.solitaire.ui.statistics.HighScoresFragment.java

/**
 * Loads the high score list/*  w  w  w.  j av a2  s .  c o m*/
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_statistics_tab2, container, false);

    //if the app got killed while the statistics are open and then the user restarts the app,
    //my helper classes aren't initialized so they can't be used. In this case, simply
    //close the statistics
    try {
        loadData();
    } catch (NullPointerException e) {
        getActivity().finish();
        return view;
    }

    TableLayout tableLayout = (TableLayout) view.findViewById(R.id.statisticsTableHighScores);
    TextView textNoEntries = (TextView) view.findViewById(R.id.statisticsTextNoEntries);

    if (scores.getHighScore(0, 0) != 0) {
        textNoEntries.setVisibility(View.GONE);
    }

    for (int i = 0; i < Scores.MAX_SAVED_SCORES; i++) { //for each entry in highScores, add a new view with it
        if (scores.getHighScore(i, 0) == 0) { //if the score is zero, don't show it
            continue;
        }

        TableRow row = (TableRow) LayoutInflater.from(getContext()).inflate(R.layout.statistics_scores_row,
                null);

        TextView textView1 = (TextView) row.findViewById(R.id.row_cell_1);
        TextView textView2 = (TextView) row.findViewById(R.id.row_cell_2);
        TextView textView3 = (TextView) row.findViewById(R.id.row_cell_3);
        TextView textView4 = (TextView) row.findViewById(R.id.row_cell_4);

        textView1.setText(String.format(Locale.getDefault(), "%s %s", scores.getHighScore(i, 0), dollar));
        long time = scores.getHighScore(i, 1);
        textView2.setText(String.format(Locale.getDefault(), "%02d:%02d:%02d", time / 3600, (time % 3600) / 60,
                (time % 60)));
        textView3.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(scores.getHighScore(i, 2)));
        textView4.setText(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(scores.getHighScore(i, 2)));

        tableLayout.addView(row);
    }

    return view;
}

From source file:de.tobiasbielefeld.solitaire.ui.statistics.RecentScoresFragment.java

/**
 * Loads the high score list//from w  w w .  j av  a 2  s  . c o  m
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_statistics_tab3, container, false);

    //if the app got killed while the statistics are open and then the user restarts the app,
    //my helper classes aren't initialized so they can't be used. In this case, simply
    //close the statistics
    try {
        loadData();
    } catch (NullPointerException e) {
        getActivity().finish();
        return view;
    }

    TableLayout tableLayout = (TableLayout) view.findViewById(R.id.statisticsTableHighScores);
    TextView textNoEntries = (TextView) view.findViewById(R.id.statisticsTextNoEntries);

    if (scores.getRecentScore(0, 2) != 0) {
        textNoEntries.setVisibility(View.GONE);
    }

    for (int i = 0; i < Scores.MAX_SAVED_SCORES; i++) { //for each entry in highScores, add a new view with it
        if (scores.getRecentScore(i, 2) == 0) { //if the score is zero, don't show it
            continue;
        }

        TableRow row = (TableRow) LayoutInflater.from(getContext()).inflate(R.layout.statistics_scores_row,
                null);

        TextView textView1 = (TextView) row.findViewById(R.id.row_cell_1);
        TextView textView2 = (TextView) row.findViewById(R.id.row_cell_2);
        TextView textView3 = (TextView) row.findViewById(R.id.row_cell_3);
        TextView textView4 = (TextView) row.findViewById(R.id.row_cell_4);

        textView1.setText(String.format(Locale.getDefault(), "%s %s", scores.getRecentScore(i, 0), dollar));
        long time = scores.getRecentScore(i, 1);
        textView2.setText(String.format(Locale.getDefault(), "%02d:%02d:%02d", time / 3600, (time % 3600) / 60,
                (time % 60)));
        textView3.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(scores.getRecentScore(i, 2)));
        textView4.setText(
                new SimpleDateFormat("HH:mm", Locale.getDefault()).format(scores.getRecentScore(i, 2)));

        tableLayout.addView(row);
    }

    return view;
}

From source file:de.micmun.android.workdaystarget.DaysLeftService.java

/**
 * Updates the days to target.//from  w w  w .  j a v  a2s. com
 */
private void updateDays() {
    AppWidgetManager appManager = AppWidgetManager.getInstance(this);
    ComponentName cName = new ComponentName(getApplicationContext(), DaysLeftProvider.class);
    int[] appIds = appManager.getAppWidgetIds(cName);

    DayCalculator dayCalc = new DayCalculator();
    if (!isOnline()) {
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            Log.e(TAG, "Interrupted: " + e.getLocalizedMessage());
        }
    }

    for (int appId : appIds) {
        PrefManager pm = new PrefManager(this, appId);
        Calendar target = pm.getTarget();
        boolean[] chkDays = pm.getCheckedDays();
        int days = pm.getLastDiff();

        if (isOnline()) {
            try {
                days = dayCalc.getDaysLeft(target.getTime(), chkDays);
                Map<String, Object> saveMap = new HashMap<String, Object>();
                Long diff = Long.valueOf(days);
                saveMap.put(PrefManager.KEY_DIFF, diff);
                pm.save(saveMap);
            } catch (JSONException e) {
                Log.e(TAG, "ERROR holidays: " + e.getLocalizedMessage());
            }
        } else {
            Log.e(TAG, "No internet connection!");
        }
        RemoteViews rv = new RemoteViews(this.getPackageName(), R.layout.appwidget_layout);
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        String targetStr = df.format(target.getTime());
        rv.setTextViewText(R.id.target, targetStr);
        String dayStr = String.format(Locale.getDefault(), "%d %s", days,
                getResources().getString(R.string.unit));
        rv.setTextViewText(R.id.dayCount, dayStr);

        // put widget id into intent
        Intent configIntent = new Intent(this, ConfigActivity.class);
        configIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        configIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appId);
        configIntent.setData(Uri.parse(configIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, configIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        rv.setOnClickPendingIntent(R.id.widgetLayout, pendIntent);

        // update widget
        appManager.updateAppWidget(appId, rv);
    }
}

From source file:org.openvpms.report.IMObjectExpressionEvaluatorTestCase.java

/**
 * Tests the {@link IMObjectExpressionEvaluator#getFormattedValue(String)}
 * method./*from  www . j  av  a2  s. co  m*/
 */
@Test
public void testGetFormattedValue() {
    IArchetypeService service = getArchetypeService();
    ILookupService lookups = getLookupService();

    Party party = createCustomer();
    ActBean act = createAct("act.customerEstimation");
    Date date = java.sql.Date.valueOf("2006-08-04");
    BigDecimal lowTotal = new BigDecimal("100");
    act.setValue("startTime", date);
    act.setValue("lowTotal", lowTotal);
    act.setParticipant("participation.customer", party);

    Functions functions = applicationContext.getBean(Functions.class);
    ExpressionEvaluator eval = new IMObjectExpressionEvaluator(act.getAct(), null, service, lookups, functions);
    String expectedDate = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
    assertEquals(expectedDate, eval.getFormattedValue("startTime"));
    assertEquals("$100.00", eval.getFormattedValue("lowTotal"));
    assertEquals("J", eval.getFormattedValue("customer.entity.firstName"));
    assertEquals("Zoo", eval.getFormattedValue("customer.entity.lastName"));

    // test [] expressions
    assertEquals("2.00", eval.getFormattedValue("[1 + 1]"));

    String expression = "[party:getBillingAddress(openvpms:get(., 'customer.entity'))]";
    assertEquals("1234 Foo St\nMelbourne VIC 3001", eval.getFormattedValue(expression));

    // test invalid nodes
    assertEquals("Invalid property name: act.customer.foo", eval.getValue("act.customer.foo"));
}

From source file:org.openvpms.report.ObjectSetExpressionEvaluatorTestCase.java

/**
 * Tests the {@link ObjectSetExpressionEvaluator#getFormattedValue(String)}
 * method.// www . j a v  a2s .co m
 */
@Test
public void testGetFormattedValue() {
    ObjectSet set = new ObjectSet();
    set.set("int", 10);
    set.set("string", "astring");
    set.set("money", new Money(100));
    Date date = java.sql.Date.valueOf("2007-01-11");
    set.set("date", date);
    IMObject customer = createCustomer("Foo", "Bar");
    set.set("act.customer", customer);

    Functions functions = applicationContext.getBean(Functions.class);
    ObjectSetExpressionEvaluator eval = new ObjectSetExpressionEvaluator(set, (PropertySet) null,
            getArchetypeService(), getLookupService(), functions);
    assertEquals("10", eval.getFormattedValue("int"));
    assertEquals("astring", eval.getFormattedValue("string"));
    assertEquals("$100.00", eval.getFormattedValue("money")); // todo localise
    String expectedDate = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
    assertEquals(expectedDate, eval.getFormattedValue("date"));
    assertEquals(customer.getName(), eval.getFormattedValue("act.customer"));
    assertEquals("Foo", eval.getFormattedValue("act.customer.firstName"));
    assertEquals("Bar", eval.getFormattedValue("act.customer.lastName"));

    // test invalid nodes
    assertEquals("Invalid object/node name: foo", eval.getFormattedValue("foo"));
    assertEquals("Invalid property name: foo", eval.getFormattedValue("act.customer.foo"));

    // test expressions
    assertEquals("2.00", eval.getFormattedValue("[1 + 1]"));
}

From source file:com.hygenics.parser.ExecuteSQL.java

/**
 * Executes SQL Commands, Unthreaded in Implementation here
 *//*  w  ww  .ja  va2 s  .  com*/
public void execute() {

    //check variables to see if they are actually system related

    if (sql != null && sql.size() > 0) {
        for (String cmd : sql) {
            try {
                log.info("Executing: " + cmd);
                this.template.execute(cmd);
            } catch (Exception e) {
                e.printStackTrace();
                if (kill) {
                    break;
                }
            }
        }
    }

    if (move != null && move.size() > 0) {
        for (String key : move.keySet()) {
            String schema = key
                    + DateFormat.getDateInstance(DateFormat.SHORT).format(Calendar.getInstance().getTime());
            template.execute(
                    "CREATE SCHEMA " + Properties.getProperty(key) + "_" + Properties.getProperty(schema));
            for (String table : move.get(key)) {
                template.execute(
                        "INSERT INTO " + Properties.getProperty(key) + "_" + Properties.getProperty(schema)
                                + "." + Properties.getProperty(table) + " VALUES(SELECT * FROM "
                                + Properties.getProperty(key) + "." + Properties.getProperty(table) + ")");
            }
        }
    }

    if (tableMappings != null) {
        for (String tableSQL : tableMappings.keySet()) {
            int lp = 0;
            String sql = null;
            String tableSelect = tableMappings.get(tableSQL);

            if (idval != null && idval.toLowerCase().trim().contains("property:")) {
                idval = System.getProperty(idval.split(":")[1].trim());
            }

            if (tableColumn.toLowerCase().trim().contains("property:")) {
                tableColumn = System.getProperty(tableColumn.split(":")[1].trim());
            }

            if (tableSchema != null && tableSchema.toLowerCase().contains("property:")) {
                tableSchema = System.getProperty(tableSchema.split(":")[1].trim());
            }

            if (tableIdentifier != null && tableIdentifier.toLowerCase().contains("property:")) {
                tableIdentifier = System.getProperty(tableIdentifier.split(":")[1].trim());
            }

            if (tableSelect.trim().toLowerCase().contains("property:")) {
                sql = "SELECT * FROM " + System.getProperty(tableSelect.split(":")[1]) + " WHERE "
                        + tableIdentifier + " LIKE '" + idval + "'";
            } else {
                sql = tableSelect;
            }

            // log.info("Executing "+sql);

            for (String record : template.getJsonData(sql)) {
                JsonObject tj = JsonObject.readFrom(record);
                if (schemaColumn != null) {
                    tableSchema = tj.get(schemaColumn).asString();
                }

                if (tj.get(tableColumn) != null && tableSchema.trim().length() > 0) {
                    String temp = Properties.getProperty(tableSQL.replace("$SCHEMA$", tableSchema));
                    temp = Properties
                            .getProperty(temp.replace("$TABLE$", tj.get(tableColumn).asString().trim()));
                    log.info("Executing " + temp);

                    if (lp > 0 && replaces != null) {
                        for (String key : replaces.keySet()) {
                            log.info(key + " " + replaces.get(key));
                            temp = temp.replaceAll(key, replaces.get(key));
                            log.info(temp);
                        }
                        log.info("Final SQL " + temp);
                    }

                    template.execute(temp);
                } else {
                    log.warn("Table name was problematic.");
                }
                lp += 1;
            }

            log.info("Tables Changed: " + lp);
        }
    }
}

From source file:com.projity.util.DateTime.java

public static DateFormat utcShortDateFormatInstance() {
    DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT);
    f.setTimeZone(DateUtils.UTC_TIME_ZONE);
    return f;//from  ww w.j  av a 2  s  .c  om
}

From source file:org.jactr.eclipse.runtime.launching.env.EnvironmentConfigurator.java

static public IFile createRuntimeEnvironmentFile(ILaunchConfiguration config, String mode,
        IProgressMonitor monitor) throws CoreException {
    /*//from ww w. j  a v a2s . c o  m
     * make sure we have runs/
     */
    IFile configurationFile = null;
    IProject project = ACTRLaunchConfigurationUtils.getProject(config);

    if (config.getAttribute(ACTRLaunchConstants.ATTR_SAVE_RUN, true)) {
        IFolder runtimeFolder = project.getFolder("runs");

        if (!runtimeFolder.exists())
            runtimeFolder.create(true, true, monitor);

        /*
         * create {now}
         */
        Date now = new Date();
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        String name = df.format(now);
        name = name.replace("/", ".");
        IFolder thisRun = runtimeFolder.getFolder(name);

        if (!thisRun.exists())
            thisRun.create(true, true, monitor);

        df = DateFormat.getTimeInstance(DateFormat.MEDIUM);
        name = df.format(now).replace(":", ".").replace(" ", "");
        thisRun = thisRun.getFolder(name);

        if (!thisRun.exists())
            thisRun.create(true, true, monitor);

        configurationFile = thisRun.getFile("environment.xml");
    } else {
        // tmp directory and temp file
        IPath workingLocation = project.getWorkingLocation(RuntimePlugin.PLUGIN_ID);
        workingLocation.append("/tmp/");
        IFolder tmpLocation = project.getFolder(workingLocation);
        tmpLocation.create(true, true, monitor);
        // TODO this could screw up if you try to run multiple instances at once
        configurationFile = tmpLocation.getFile(project.getName() + "-environment.xml");
    }

    return configurationFile;
}

From source file:com.espian.ticktock.AddEditActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    try {/*from w  w  w.j ava2s.  c  o  m*/
        data.moveToFirst();
        Date editableDate = DateFormat.getDateInstance(DateFormat.LONG).parse(data.getString(2));
        mDatePicker.init(editableDate, new Date(), mMaxDate.getTime());
        mTitle.setText(data.getString(1));
        mHelper.show();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this, R.string.load_date_exception, Toast.LENGTH_SHORT).show();
    }

}

From source file:org.kuali.coeus.common.questionnaire.framework.answer.SaveQuestionnaireAnswerRule.java

private boolean validateAttributeFormat(Answer answer, String errorKey, int questionIndex) {
    boolean valid = true;

    ValidationPattern validationPattern = VALIDATION_CLASSES
            .get(answer.getQuestion().getQuestionTypeId().toString());

    // if there is no data type matched, then set error ?
    Pattern validationExpression = validationPattern.getRegexPattern();

    String validFormat = getValidFormat(answer.getQuestion().getQuestionTypeId().toString());

    if (validFormat.equals(Constants.DATA_TYPE_STRING) || validFormat.equals(Constants.DATA_TYPE_NUMBER)) {
        if (!validationExpression.matcher(answer.getAnswer()).matches()) {
            GlobalVariables.getMessageMap().putError(errorKey, KeyConstants.ERROR_INVALID_FORMAT_WITH_FORMAT,
                    new String[] { ANSWER + (questionIndex + 1), answer.getAnswer(), validFormat });
            valid = false;/*  w w w  . j  a  va2s.com*/
        }
    } else if (validFormat.equals(Constants.DATA_TYPE_DATE)) {
        try {
            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
            dateFormat.setLenient(false);
            dateFormat.parse(answer.getAnswer());
        } catch (ParseException e) {
            GlobalVariables.getMessageMap().putError(errorKey, RiceKeyConstants.ERROR_INVALID_FORMAT,
                    ANSWER + (questionIndex + 1), answer.getAnswer(), validFormat);
            valid = false;
        }
    }

    return valid;
}