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(int dateStyle, int timeStyle, Locale aLocale) 

Source Link

Document

Gets the date/time formatter with the given formatting styles for the given locale.

Usage

From source file:desmoj.extensions.grafic.util.Plotter.java

/**
 * configure domainAxis (label, timeZone, locale, tick labels)
 * of time-series chart/*  w w w  . j  ava  2s.  co  m*/
 * @param dateAxis
 */
private void configureDomainAxis(DateAxis dateAxis) {
    if (this.begin != null)
        dateAxis.setMinimumDate(this.begin);
    if (this.end != null)
        dateAxis.setMaximumDate(this.end);
    dateAxis.setTimeZone(this.timeZone);

    Date dateMin = dateAxis.getMinimumDate();
    Date dateMax = dateAxis.getMaximumDate();
    //DateFormat formatter = new SimpleDateFormat("d.MM.yyyy HH:mm:ss.SSS");;
    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM, locale);
    String label = "Time: " + formatter.format(dateMin) + " .. " + formatter.format(dateMax);
    formatter = new SimpleDateFormat("z");
    label += " " + formatter.format(dateMax);
    dateAxis.setLabel(label);

    TimeInstant max = new TimeInstant(dateMax);
    TimeInstant min = new TimeInstant(dateMin);
    TimeSpan diff = TimeOperations.diff(max, min);

    if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.DAYS)))
        formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
    else if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.HOURS)))
        formatter = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    else if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.MINUTES)))
        formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
    else
        formatter = new SimpleDateFormat("HH:mm:ss.SSS");
    dateAxis.setDateFormatOverride(formatter);
    dateAxis.setVerticalTickLabels(true);
}

From source file:net.wastl.webmail.storage.FileStorage.java

protected String formatDate(long date) {
    if (df == null) {
        TimeZone tz = TimeZone.getDefault();
        df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.DEFAULT, Locale.getDefault());
        df.setTimeZone(tz);/*w  w w.j  av a2s . co m*/
    }
    String now = df.format(new Date(date));
    return now;
}

From source file:mitm.common.security.certificate.GenerateTestCertificates.java

private void generateCertificateCriticalExtendedKeyUsage() throws Exception {
    X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

    String encodedPrivateKey = "30820276020100300d06092a864886f70d0101010500048202603082025c"
            + "0201000281810096990cdd93c7bd2ca4d406285833cd356cc668f2571338"
            + "46fb4dfc885f275bdfb9bf45d539f89e826e442c0a750206a33d40600711"
            + "09ba96eb400710edf90590604e13ff7b624001b4b75c3fd388d18bcd71b4"
            + "c3e4a06c08da3fed5365db5d08cfb10321235da904886ea0329dbf041fa1"
            + "890f97d2b53a366f643dd344cc2e69020301000102818050ee10d6e67ad9"
            + "73ab6471a6aeb7afd8bd0ae70d0cb43c7310cbf9210419afaacc3438fffc"
            + "765a2077c754ef8dafb807737c2bdec04e3d22ab6bae206ff27a05284a96"
            + "015d5437739ffdb6801f537b7b7406e6088a56324105bce1fcfc86bc8a29"
            + "e9adb0ae4152d23f695bfe585557d73da61bf7eb7c1bbdc164afed60e54e"
            + "bd024100ca4e8e4e7e905e4b273d1381f4323ce673d5d33ce5a75f46d719"
            + "8c4ea1bcc13b621f314fa6166cc6193ff912814c54a717b93804b258ec44"
            + "d0a212d371078cdf024100be9133919b1093a3d8c7afa1ff70ab769076c9"
            + "aeb5c548cdc9aef63812a57eccf77f0def9c979cfaf117d8ffb454f823de"
            + "245a1b90da34adaf57b8a561fde5b702407d8dcd51b7c89f4ca2f88bbfce"
            + "2ed38eee7ad8d3656fbf78b68c1b80bd6de8ba9305ead394af3c28a1890b"
            + "6a49a676af10d1198c08a7995287ecde242d74d31f024032a09ac5ad1f8b"
            + "49b536dfc736f8b4e4cbde7318523c366a4d9188e23eb9eee4ff3fa6f128"
            + "75f3038bf79cf3d9f1d4f69a76a7e5b8e6efa5d0f68a1c8ddb0923024100"
            + "b44f03887aa2d95203f3dee44298b12b90c163bffebdc077551208c53987"
            + "11e35c60f8d6348f7fd51f7a384bb397ead4957e37b0440addecc19f9fac" + "b129564b";

    String encodedPublicKey = "30819f300d06092a864886f70d010101050003818d003081890281810096"
            + "990cdd93c7bd2ca4d406285833cd356cc668f257133846fb4dfc885f275b"
            + "dfb9bf45d539f89e826e442c0a750206a33d4060071109ba96eb400710ed"
            + "f90590604e13ff7b624001b4b75c3fd388d18bcd71b4c3e4a06c08da3fed"
            + "5365db5d08cfb10321235da904886ea0329dbf041fa1890f97d2b53a366f" + "643dd344cc2e690203010001";

    PrivateKey privateKey = decodePrivateKey(encodedPrivateKey);
    PublicKey publicKey = decodePublicKey(encodedPublicKey);

    X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder();

    String email = "test@example.com";

    subjectBuilder.setCommonName("Valid certificate");
    subjectBuilder.setEmail(email);/*from w w  w  .  j  av a2s .  c o  m*/
    subjectBuilder.setCountryCode("NL");
    subjectBuilder.setLocality("Amsterdam");
    subjectBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();
    altNamesBuider.setRFC822Names(email);

    X500Principal subject = subjectBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    // use TreeSet because we want a deterministic certificate (ie. hash should not change)
    Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.DIGITALSIGNATURE);
    keyUsage.add(KeyUsageType.KEYENCIPHERMENT);
    keyUsage.add(KeyUsageType.NONREPUDIATION);

    Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);

    BigInteger serialNumber = new BigInteger("116a448f117ff69fe4f2d4d38f689d7", 16);

    Date now = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK)
            .parse("21-Nov-2007 10:38:35");

    certificateBuilder.setSubject(subject);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setKeyUsage(keyUsage, true);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true /* critical */);
    certificateBuilder.setNotBefore(DateUtils.addDays(now, -20));
    certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
    certificateBuilder.setPublicKey(publicKey);
    certificateBuilder.setSerialNumber(serialNumber);
    certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateBuilder.addSubjectKeyIdentifier(true);

    X509Certificate certificate = certificateBuilder.generateCertificate(caPrivateKey, caCertificate);

    assertNotNull(certificate);

    certificates.add(certificate);

    Certificate[] chain = new Certificate[] { certificate, caCertificate, rootCertificate };

    keyStore.setKeyEntry("CriticalEKU", privateKey, null, chain);
}

From source file:org.streets.commons.util.FastDateFormat.java

/**
 * <p>Gets a date/time formatter instance using the specified style,
 * time zone and locale.</p>/*  ww  w.  j  a va 2  s  .  co m*/
 *
 * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted date
 * @param locale  optional locale, overrides system locale
 * @return a localized standard date/time formatter
 * @throws IllegalArgumentException if the Locale has no date/time
 *  pattern defined
 */
public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone,
        Locale locale) {

    Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle));
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }
    if (locale != null) {
        key = new Pair(key, locale);
    }

    FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle,
                    locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateTimeInstanceCache.put(key, format);

        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date time pattern for locale: " + locale);
        }
    }
    return format;
}

From source file:de.uniwue.info6.webapp.lists.ExGroupTableBean.java

/**
 *
 *
 * @param ex/*from  ww  w.j a v  a  2  s. c  om*/
 * @return
 */
public String getLastUserEntryTime(Exercise ex) {
    UserEntry entry = userEntryDao.getLastUserEntry(ex);
    if (entry != null) {
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL,
                new Locale("de", "DE"));
        return df.format(entry.getEntryTime());
    }
    return null;
}

From source file:org.opencms.workflow.CmsExtendedWorkflowManager.java

/**
 * Generates the description for a new workflow project based on the user for whom it is created.<p>
 *
 * @param userCms the user's current CMS context
 *
 * @return the workflow project description
 *///from www .  j  a  v  a 2  s .c om
protected String generateProjectDescription(CmsObject userCms) {

    CmsUser user = userCms.getRequestContext().getCurrentUser();
    OpenCms.getLocaleManager();
    Locale locale = CmsLocaleManager.getDefaultLocale();
    long time = System.currentTimeMillis();
    Date date = new Date(time);
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
    String dateString = format.format(date);
    String result = Messages.get().getBundle(locale).key(Messages.GUI_WORKFLOW_PROJECT_DESCRIPTION_2,
            user.getName(), dateString);
    return result;
}

From source file:no.abmu.abmstatistikk.annualstatistic.service.hibernate2.AnnualStatisticServiceHelper.java

private void timeStampReport(Map<String, Object> report) {
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM,
            LocaleTypeNameConst.BOKMAAL);

    report.put("timestamp", dateFormat.format(new Date()));
}

From source file:net.sourceforge.vulcan.core.support.AbstractProjectDomBuilder.java

private void addTimestampNode(final Element parent, String nodeName, final Date date, final DateFormat format,
        Locale locale) {/*w  w w.  java2  s .c  o  m*/
    if (date != null) {
        final DateFormat textualDateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT,
                locale);

        final Element timestampNode = addChildNodeWithText(parent, nodeName, format.format(date));
        timestampNode.setAttribute("millis", Long.toString(date.getTime()));
        timestampNode.setAttribute("text", textualDateFormat.format(date));
    }
}

From source file:org.freeplane.features.format.FormatController.java

private SimpleDateFormat createDefaultDateTimeFormat(String datetimePattern) {
    final String[] styles = datetimePattern.split("\\s*,\\s*");
    if (styles.length == 2 && getDateStyle(styles[0]) != null && getDateStyle(styles[1]) != null)
        return (SimpleDateFormat) DateFormat.getDateTimeInstance(getDateStyle(styles[0]),
                getDateStyle(styles[1]), FormatUtils.getFormatLocaleFromResources());
    else//from  ww  w.j ava 2s.com
        return getDateFormat(datetimePattern);
}

From source file:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java

/**
 * localize a string value depending on datatype and locale
 *
 * @param owner the BindingElement which is localized
 * @param type  the datatype of the bound Node
 * @param value the string value to convert
 * @return returns a localized representation of the input string
 *///  w  ww. ja v a2 s.co  m
public static String localiseValue(BindingElement owner, Element state, String type, String value)
        throws XFormsException {
    if (value == null || value.equals("")) {
        return value;
    }
    String tmpType = type;
    if (tmpType != null && tmpType.contains(":")) {
        tmpType = tmpType.substring(tmpType.indexOf(":") + 1, tmpType.length());
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N, "true").equals("true")) {

        Locale locale = (Locale) owner.getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        if (tmpType == null) {
            tmpType = owner.getModelItem().getDeclarationView().getDatatype();
        }
        if (tmpType == null) {
            LOGGER.debug(DOMUtil.getCanonicalPath(owner.getInstanceNode()) + " has no type, assuming 'string'");
            return value;
        }
        if (tmpType.equalsIgnoreCase("float") || tmpType.equalsIgnoreCase("decimal")
                || tmpType.equalsIgnoreCase("double")) {
            if (value.equals(""))
                return value;
            if (value.equals("NaN"))
                return value; //do not localize 'NaN' as it returns strange characters
            try {
                NumberFormat formatter = NumberFormat.getNumberInstance(locale);
                if (formatter instanceof DecimalFormat) {
                    //get original number format
                    int separatorPos = value.indexOf(".");
                    if (separatorPos == -1) {
                        formatter.setMaximumFractionDigits(0);
                    } else {
                        int fractionDigitCount = value.length() - separatorPos - 1;
                        formatter.setMinimumFractionDigits(fractionDigitCount);
                    }

                    Double num = Double.parseDouble(value);
                    return formatter.format(num.doubleValue());
                }
            } catch (NumberFormatException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("date")) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date d = sf.parse(value);
                return DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(d);
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("dateTime")) {

            //hackery due to lacking pattern for ISO 8601 Timezone representation in SimpleDateFormat
            String timezone = "";
            String dateTime = null;
            if (value.contains("GMT")) {
                timezone = " GMT" + value.substring(value.lastIndexOf(":") - 3, value.length());
                int devider = value.lastIndexOf(":");
                dateTime = value.substring(0, devider) + value.substring(devider + 1, value.length());
            } else if (value.contains("Z")) {
                timezone = "";
                dateTime = value.substring(0, value.indexOf("Z"));

            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());
                dateTime = value.substring(0, value.indexOf("+"));

            } else {
                dateTime = value;
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

            try {
                Date d = sf.parse(dateTime);
                return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale).format(d)
                        + timezone;
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else {
            //not logging for type 'string'
            if (LOGGER.isTraceEnabled() && !(tmpType.equals("string"))) {
                LOGGER.trace("Type " + tmpType + " cannot be localized");
            }
        }
    }
    return value;
}