Example usage for java.text DateFormat getDateTimeInstance

List of usage examples for java.text DateFormat getDateTimeInstance

Introduction

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

Prototype

public static final DateFormat getDateTimeInstance() 

Source Link

Document

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

Usage

From source file:net.sf.jabb.web.action.VfsTreeAction.java

/**
 * It transforms FileObject into JsTreeNodeData.
 * @param file  the file whose information will be encapsulated in the node data structure.
 * @return   The node data structure which presents the file.
 * @throws FileSystemException //from   w w w .  j a v a2 s  .co m
 */
protected JsTreeNodeData populateTreeNodeData(FileObject file, boolean noChild, String relativePath)
        throws FileSystemException {
    JsTreeNodeData node = new JsTreeNodeData();

    String baseName = file.getName().getBaseName();
    FileContent content = file.getContent();
    FileType type = file.getType();

    node.setData(baseName);

    Map<String, Object> attr = new HashMap<String, Object>();
    node.setAttr(attr);
    attr.put("id", relativePath);
    attr.put("rel", type.getName());
    attr.put("fileType", type.getName());
    if (content != null) {
        long fileLastModifiedTime = file.getContent().getLastModifiedTime();
        attr.put("fileLastModifiedTime", fileLastModifiedTime);
        attr.put("fileLastModifiedTimeForDisplay",
                DateFormat.getDateTimeInstance().format(new Date(fileLastModifiedTime)));
        if (file.getType() != FileType.FOLDER) {
            attr.put("fileSize", content.getSize());
            attr.put("fileSizeForDisplay", FileUtils.byteCountToDisplaySize(content.getSize()));
        }
    }

    // these fields should not appear in JSON for leaf nodes
    if (!noChild) {
        node.setState(JsTreeNodeData.STATE_CLOSED);
    }
    return node;
}

From source file:org.apache.myfaces.tomahawk.util.ErrorPageWriter.java

public static void debugHtml(Writer writer, FacesContext faces, List exceptionList) throws IOException {
    init(faces);//  w  w  w .  jav a2 s  .c om
    Date now = new Date();
    for (int i = 0; i < ERROR_PARTS.length; i++) {
        if ("message".equals(ERROR_PARTS[i])) {
            for (int j = 0; j < exceptionList.size(); j++) {
                Exception e = (Exception) exceptionList.get(j);
                String msg = e.getMessage();
                if (msg != null) {
                    writer.write(msg.replaceAll("<", TS));
                } else {
                    writer.write(e.getClass().getName());
                }
                if (!(j + 1 == exceptionList.size())) {
                    writer.write("<br>");
                }
            }
        } else if ("trace".equals(ERROR_PARTS[i])) {
            for (int j = 0; j < exceptionList.size(); j++) {
                Exception e = (Exception) exceptionList.get(j);
                writeException(writer, e);
            }
        } else if ("now".equals(ERROR_PARTS[i])) {
            writer.write(DateFormat.getDateTimeInstance().format(now));
        } else if ("tree".equals(ERROR_PARTS[i])) {
            if (faces.getViewRoot() != null) {
                List highlightId = null;
                for (int j = 0; j < exceptionList.size(); j++) {
                    Exception e = (Exception) exceptionList.get(j);
                    if (highlightId == null) {
                        highlightId = getErrorId(e);
                    } else {
                        highlightId.addAll(getErrorId(e));
                    }
                }
                writeComponent(writer, faces.getViewRoot(), highlightId);
            }
        } else if ("vars".equals(ERROR_PARTS[i])) {
            writeVariables(writer, faces);
        } else if ("cause".equals(ERROR_PARTS[i])) {
            for (int j = 0; j < exceptionList.size(); j++) {
                Exception e = (Exception) exceptionList.get(j);
                writeCause(writer, e);
                if (!(j + 1 == exceptionList.size())) {
                    writer.write("<br>");
                }
            }
        } else {
            writer.write(ERROR_PARTS[i]);
        }
    }
}

From source file:com.bonsai.wallet32.WalletService.java

private MyDownloadListener mkDownloadListener() {
    return new MyDownloadListener() {
        protected void progress(double pct, int blocksToGo, Date date, long msecsLeft) {
            Date cmplDate = new Date(System.currentTimeMillis() + msecsLeft);
            mLogger.info(String.format("CHAIN DOWNLOAD %d%% DONE WITH %d BLOCKS TO GO, " + "COMPLETE AT %s",
                    (int) pct, blocksToGo, DateFormat.getDateTimeInstance().format(cmplDate)));
            mBlocksToGo = blocksToGo;//from w  w  w .  ja v  a  2  s. co  m
            mScanDate = date;
            mMsecsLeft = msecsLeft;
            if (mPercentDone != pct) {
                mPercentDone = pct;
                setState(State.SYNCING);
            }
        }
    };
}

From source file:com.taobao.adfs.database.tdhsocket.client.util.ConvertUtil.java

public static Long getTimeFromString(String stringVal, @Nullable Calendar cal) throws SQLException {
    if (stringVal == null) {
        return null;
    }/*from   ww w  .j  ava  2s . c  om*/
    String val = stringVal.trim();
    if (val.length() == 0) {
        return null;
    }
    if (val.equals("0") || val.equals("0000-00-00") || val.equals("0000-00-00 00:00:00")
            || val.equals("00000000000000") || val.equals("0")) {
        Calendar calendar = null;
        if (cal != null) {
            calendar = Calendar.getInstance(cal.getTimeZone());
        } else {
            calendar = Calendar.getInstance();
        }
        calendar.set(Calendar.YEAR, 1);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTimeInMillis();
    }

    DateFormat dateFormat = DateFormat.getDateTimeInstance();
    if (cal != null) {
        TimeZone timeZone = cal.getTimeZone();
        dateFormat.setTimeZone(timeZone);
    }
    try {
        return dateFormat.parse(val).getTime();
    } catch (ParseException e) {
        throw new SQLException("Parse date failure:" + val);
    }
}

From source file:bluej.collect.DataCollectorImpl.java

private static synchronized void submitEvent(final Project project, final Package pkg,
        final EventName eventName, final Event evt) {
    final String projectName = project == null ? null : project.getProjectName();
    final String projectPathHash = project == null ? null
            : CollectUtility.md5Hash(project.getProjectDir().getAbsolutePath());
    final String packageName = pkg == null ? null : pkg.getQualifiedName();

    // We take a copy of these internal variables, so that we don't have a race hazard
    // if the variable changes between now and the event being sent:
    final String uuidCopy = DataCollector.getUserID();
    final String experimentCopy = DataCollector.getExperimentIdentifier();
    final String participantCopy = DataCollector.getParticipantIdentifier();

    /**//from ww w .ja v a  2s. c o m
     * Wrap the Event we've been given to add the other normal expected fields:
     */
    DataSubmitter.submitEvent(new Event() {

        @Override
        public void success(Map<FileKey, List<String>> fileVersions) {
            evt.success(fileVersions);
        }

        @Override
        public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) {
            MultipartEntity mpe = evt.makeData(sequenceNum, fileVersions);

            if (mpe == null)
                return null;

            mpe.addPart("user[uuid]", CollectUtility.toBody(uuidCopy));
            mpe.addPart("session[id]", CollectUtility.toBody(DataCollector.getSessionUuid()));
            mpe.addPart("participant[experiment]", CollectUtility.toBody(experimentCopy));
            mpe.addPart("participant[participant]", CollectUtility.toBody(participantCopy));

            if (projectName != null) {
                mpe.addPart("project[name]", CollectUtility.toBody(projectName));
                mpe.addPart("project[path_hash]", CollectUtility.toBody(projectPathHash));

                if (packageName != null) {
                    mpe.addPart("package[name]", CollectUtility.toBody(packageName));
                }
            }

            mpe.addPart("event[source_time]",
                    CollectUtility.toBody(DateFormat.getDateTimeInstance().format(new Date())));
            mpe.addPart("event[name]", CollectUtility.toBody(eventName.getName()));
            mpe.addPart("event[sequence_id]", CollectUtility.toBody(Integer.toString(sequenceNum)));

            return mpe;
        }
    });
}

From source file:org.opendatakit.briefcase.util.WebUtils.java

/**
 * Parse a string into a datetime value. Tries the common Http formats, the
 * iso8601 format (used by Javarosa), the default formatting from
 * Date.toString(), and a time-only format.
 * /*w  w w . ja  va 2s  . c om*/
 * @param value
 * @return
 */
public static final Date parseDate(String value) {
    if (value == null || value.length() == 0)
        return null;

    String[] iso8601Pattern = new String[] { PATTERN_ISO8601 };

    String[] localizedParsePatterns = new String[] {
            // try the common HTTP date formats that have time zones
            PATTERN_RFC1123, PATTERN_RFC1036, PATTERN_DATE_TOSTRING };

    String[] localizedNoTzParsePatterns = new String[] {
            // ones without timezones... (will assume UTC)
            PATTERN_ASCTIME };

    String[] tzParsePatterns = new String[] { PATTERN_ISO8601, PATTERN_ISO8601_DATE, PATTERN_ISO8601_TIME };

    String[] noTzParsePatterns = new String[] {
            // ones without timezones... (will assume UTC)
            PATTERN_ISO8601_WITHOUT_ZONE, PATTERN_NO_DATE_TIME_ONLY,
            PATTERN_YYYY_MM_DD_DATE_ONLY_NO_TIME_DASH };

    Date d = null;
    // iso8601 parsing is sometimes off-by-one when JR does it...
    d = parseDateSubset(value, iso8601Pattern, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try to parse with the JavaRosa parsers
    d = DateUtils.parseDateTime(value);
    if (d != null)
        return d;
    d = DateUtils.parseDate(value);
    if (d != null)
        return d;
    d = DateUtils.parseTime(value);
    if (d != null)
        return d;
    // try localized and english text parsers (for Web headers and interactive filter spec.)
    d = parseDateSubset(value, localizedParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedNoTzParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedNoTzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try other common patterns that might not quite match JavaRosa parsers
    d = parseDateSubset(value, tzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, noTzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try the locale- and timezone- specific parsers
    {
        DateFormat formatter = DateFormat.getDateTimeInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    {
        DateFormat formatter = DateFormat.getDateInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    {
        DateFormat formatter = DateFormat.getTimeInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    throw new IllegalArgumentException("Unable to parse the date: " + value);
}

From source file:org.opencms.newsletter.CmsNewsletter.java

/**
 * Replaces the macros in the given message.<p>
 * /*from  w  ww .j a  v a 2  s.  c  o  m*/
 * @param msg the message in which the macros are replaced
 * @param recipient the recipient in the message
 * 
 * @return the message with the macros replaced
 */
private String replaceMacros(String msg, I_CmsNewsletterRecipient recipient) {

    CmsMacroResolver resolver = CmsMacroResolver.newInstance();
    resolver.addMacro(MACRO_USER_FIRSTNAME, recipient.getFirstname());
    resolver.addMacro(MACRO_USER_LASTNAME, recipient.getLastname());
    resolver.addMacro(MACRO_USER_FULLNAME, recipient.getFullName());
    resolver.addMacro(MACRO_USER_EMAIL, recipient.getEmail());
    resolver.addMacro(MACRO_SEND_DATE,
            DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis())));
    return resolver.resolveMacros(msg);
}

From source file:com.nextgis.maplibui.control.DateTime.java

@Override
public void init(Field field, Bundle savedState, Cursor featureCursor) {
    if (null != field) {
        mFieldName = field.getName();/*w  ww  .  j  a va  2 s .  c om*/
    }

    switch (mPickerType) {

    case GeoConstants.FTDate:
        mDateFormat = (SimpleDateFormat) DateFormat.getDateInstance();
        break;

    case GeoConstants.FTTime:
        mDateFormat = (SimpleDateFormat) DateFormat.getTimeInstance();
        break;

    default:
        mPickerType = GeoConstants.FTDateTime;
    case GeoConstants.FTDateTime:
        mDateFormat = (SimpleDateFormat) DateFormat.getDateTimeInstance();
        break;
    }

    String text = "";

    if (ControlHelper.hasKey(savedState, mFieldName)) {
        mValue = savedState.getLong(ControlHelper.getSavedStateKey(mFieldName));
    } else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);
        if (column >= 0) {
            mValue = featureCursor.getLong(column);
        }
    }

    if (null != mValue) {
        text = getText();
    }

    setText(text);
    setSingleLine(true);
    setFocusable(false);
    setOnClickListener(getDateUpdateWatcher(mPickerType));

    String pattern = mDateFormat.toLocalizedPattern();
    setHint(pattern);
}

From source file:org.ntpsync.service.NtpSyncService.java

private void handleResult(final Message message) {
    Log.d(Constants.TAG, "Handle message directly in NtpSyncService...");

    // we need a looper to get toasts displayed from service!
    Handler handler = new Handler(Looper.getMainLooper());

    handler.post(new Runnable() {
        public void run() {
            DateFormat df = DateFormat.getDateTimeInstance();

            switch (message.arg1) {
            case NtpSyncService.RETURN_GENERIC_ERROR:
                Toast.makeText(getApplicationContext(),
                        getString(R.string.app_name) + ": " + getString(R.string.return_generic_error),
                        Toast.LENGTH_LONG).show();

                break;

            case NtpSyncService.RETURN_OKAY:

                Bundle returnData = message.getData();
                final Date newTime = (Date) returnData.getSerializable(NtpSyncService.MESSAGE_DATA_TIME);

                Toast.makeText(/*from  www.  j a  v a2  s  .  com*/
                        getApplicationContext(), getString(R.string.app_name) + ": "
                                + getString(R.string.return_set_time) + " " + df.format(newTime),
                        Toast.LENGTH_LONG).show();

                break;

            case NtpSyncService.RETURN_SERVER_TIMEOUT:
                Toast.makeText(getApplicationContext(),
                        getString(R.string.app_name) + ": " + getString(R.string.return_timeout),
                        Toast.LENGTH_LONG).show();

                break;

            case NtpSyncService.RETURN_NO_ROOT:
                Toast.makeText(getApplicationContext(),
                        getString(R.string.app_name) + ": " + getString(R.string.return_no_root),
                        Toast.LENGTH_LONG).show();

                break;

            default:
                break;
            }
        }
    });
}

From source file:com.r.raul.tools.MainActivity.java

public static String getAppTimeStamp(Context context) {
    String timeStamp = "";

    try {// ww  w.  ja  va2s. co m
        ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        String appFile = appInfo.sourceDir;
        long time = new File(appFile).lastModified();

        DateFormat formatter = DateFormat.getDateTimeInstance();
        timeStamp = formatter.format(time);

    } catch (Exception e) {

    }

    return timeStamp;

}