Example usage for org.joda.time.format ISODateTimeFormat dateTimeNoMillis

List of usage examples for org.joda.time.format ISODateTimeFormat dateTimeNoMillis

Introduction

In this page you can find the example usage for org.joda.time.format ISODateTimeFormat dateTimeNoMillis.

Prototype

public static DateTimeFormatter dateTimeNoMillis() 

Source Link

Document

Returns a formatter that combines a full date and time without millis, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ssZZ).

Usage

From source file:org.codice.ddf.spatial.ogc.wfs.v2_0_0.catalog.source.WfsFilterDelegate.java

License:Open Source License

private String convertDateToIso8601Format(Date inputDate) {
    DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC);
    return dtf.print(new DateTime(inputDate)).toString();
}

From source file:org.cook_e.cook_e.BugReportActivity.java

License:Open Source License

/**
 * Starts the process of sending an E-mail message with the report
 * @param report the report to send//w w w  . j  a va2s.co m
 */
private void mailReport(BugReport report) {

    final StringBuilder message = new StringBuilder();
    final DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis();
    message.append("Time: ");
    formatter.printTo(message, report.getDate());
    message.append('\n');
    message.append("User description: ");
    message.append(report.getDesc());
    message.append("\nMetadata: ");
    message.append(report.getMeta());

    ShareCompat.IntentBuilder.from(this).setType("message/rfc822").addEmailTo(REPORT_ADDRESS)
            .setSubject("Cook-E Problem Report").setText(message).setChooserTitle(R.string.mail_report)
            .startChooser();
    finish();
}

From source file:org.ddialliance.ddiftp.util.Translator.java

License:Open Source License

/**
 * Format an ISO8601 time string defined by into a Calendar<BR>
 * Defined by '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
 * (zzzzzz)?//from ww  w  .  j av a 2  s  .  c  o m
 * 
 * @see http://www.w3.org/TR/xmlschema-2/#dateTime
 * @param time
 *            string
 * @return calendar
 * @throws DDIFtpException
 */
public static Calendar formatIso8601DateTime(String time) throws DDIFtpException {
    // yyyy-MM-dd'T'HH:mm:ss.SSSZZ full format
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    try {
        DateTime dateTime = fmt.parseDateTime(time);
        return dateTime.toCalendar(getLocale());
    } catch (IllegalArgumentException e) {
        try {
            // yyyy-MM-dd'T'HH:mm:ssZZ with out millisecond
            fmt = ISODateTimeFormat.dateTimeNoMillis();
            fmt.withLocale(getLocale());
            fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
            DateTime dateTime = fmt.parseDateTime(time);
            return dateTime.toCalendar(getLocale());
        } catch (IllegalArgumentException e1) {
            try {
                // yyyy-MM-dd'T'HH:mm:ss.SS with out time zone
                fmt = ISODateTimeFormat.dateHourMinuteSecondFraction();
                fmt.withLocale(getLocale());
                fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                DateTime dateTime = fmt.parseDateTime(time);
                return dateTime.toCalendar(getLocale());
            } catch (Exception e2) {
                try {
                    // yyyy-MM-dd'T'HH:mm:ss with out millisecond and time
                    // zone
                    fmt = ISODateTimeFormat.dateHourMinuteSecond();
                    fmt.withLocale(getLocale());
                    fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                    DateTime dateTime = fmt.parseDateTime(time);
                    return dateTime.toCalendar(getLocale());
                } catch (IllegalArgumentException e3) {
                    try {
                        fmt = ISODateTimeFormat.dateParser();
                        fmt.withLocale(getLocale());
                        fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                        DateTime dateTime = fmt.parseDateTime(time);
                        return dateTime.toCalendar(getLocale());
                    } catch (Exception e4) {
                        throw new DDIFtpException("translate.timeformat.error",
                                new Object[] { time,
                                        "'-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?" },
                                e);
                    }
                }
            }
        }
    }
}

From source file:org.devgateway.eudevfin.sheetexp.iati.transformer.IatiTransformer.java

License:Open Source License

@ServiceActivator(inputChannel = "iatiListExporterChannel")
public Boolean createIatiExportManually(final List<EntityWrapperInterface<CustomFinancialTransaction>> list,
        @Header("outputStream") final OutputStream out, @Header("exportName") final String exportName) {

    final IatiTransformerEngine engine = new IatiTransformerEngine(list);

    final IatiActivities iatiActivities = engine.transform().getIatiActivities();

    final DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis();
    final DateTime now = new DateTime().millisOfSecond().withMinimumValue();
    final XStream xStream = new XStream();

    xStream.processAnnotations(IatiActivities.class);
    xStream.registerConverter(new DateConverter("yyyy-MM-dd", new String[] {}));

    try (final OutputStreamWriter writer = new OutputStreamWriter(out, Charset.forName("UTF-8"))) {
        writer.write(String.format("<iati-activities generated-datetime=\"%s\" version=\"1.04\">",
                formatter.print(now)));//from   w  w  w .j a  va 2 s  .  c  om
        writer.write("<!-- Generated By EUDEVFIN -->");
        for (final IatiActivity iatiActivity : iatiActivities.getActivities()) {
            final String xml = xStream.toXML(iatiActivity);
            writer.write(xml);
        }
        writer.write("</iati-activities>");
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.dspace.authority.AuthorityValue.java

License:BSD License

public List<DateTimeFormatter> getDateFormatters() {
    List<DateTimeFormatter> list = new ArrayList<DateTimeFormatter>();
    list.add(ISODateTimeFormat.dateTime());
    list.add(ISODateTimeFormat.dateTimeNoMillis());
    return list;/*w w w . ja  v  a 2  s  .  com*/
}

From source file:org.dspace.content.Item.java

License:BSD License

/**
 * Withdraw the item from the archive. It is kept in place, and the content
 * and metadata are not deleted, but it is not publicly accessible.
 *
 * @throws SQLException/*from w  w w.  j  ava2  s  .c o m*/
 * @throws AuthorizeException
 * @throws IOException
 */
public void withdraw() throws SQLException, AuthorizeException, IOException {
    // Check permission. User either has to have REMOVE on owning collection
    // or be COLLECTION_EDITOR of owning collection
    AuthorizeManager.authorizeWithdrawItem(context, this);

    String timestamp = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC)
            .print(System.currentTimeMillis());

    // Add suitable provenance - includes user, date, collections +
    // bitstream checksums
    EPerson e = context.getCurrentUser();

    // Build some provenance data while we're at it.
    StringBuilder prov = new StringBuilder();

    prov.append("Item withdrawn by ").append(e.getFullName()).append(" (").append(e.getEmail()).append(") on ")
            .append(timestamp).append("\n").append("Item was in collections:\n");

    for (Collection coll : getCollections()) {
        prov.append(coll.getMetadata("name")).append(" (ID: ").append(coll.getID()).append(")\n");
    }

    // Set withdrawn flag. timestamp will be set; last_modified in update()
    tableRow.setColumn("withdrawn", true);

    // in_archive flag is now false
    tableRow.setColumn("in_archive", false);

    prov.append(InstallItem.getBitstreamProvenanceMessage(this));

    addMetadata("dc", "description", "provenance", "en", prov.toString());

    // Update item in DB
    update();

    context.addContentEvent(this, EventType.WITHDRAW);

    // and all of our authorization policies
    // FIXME: not very "multiple-inclusion" friendly
    AuthorizeManager.removeAllPolicies(context, this);

    // Write log
    log.info(LogManager.getHeader(context, "withdraw_item", "user=" + e.getEmail() + ",item_id=" + getID()));
}

From source file:org.dspace.content.Item.java

License:BSD License

/**
 * Reinstate a withdrawn item//w ww. j  a  v a  2 s. co m
 *
 * @throws SQLException
 * @throws AuthorizeException
 * @throws IOException
 */
public void reinstate() throws SQLException, AuthorizeException, IOException {
    // check authorization
    AuthorizeManager.authorizeReinstateItem(context, this);

    String timestamp = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC)
            .print(System.currentTimeMillis());

    // Check permission. User must have ADD on all collections.
    // Build some provenance data while we're at it.

    // Add suitable provenance - includes user, date, collections +
    // bitstream checksums
    EPerson e = context.getCurrentUser();
    StringBuilder prov = new StringBuilder();
    prov.append("Item reinstated by ").append(e.getFullName()).append(" (").append(e.getEmail()).append(") on ")
            .append(timestamp).append("\n").append("Item was in collections:\n");

    List<Collection> colls = getCollections();
    for (Collection coll : colls) {
        prov.append(coll.getMetadata("name")).append(" (ID: ").append(coll.getID()).append(")\n");
    }

    // Clear withdrawn flag
    tableRow.setColumn("withdrawn", false);

    // in_archive flag is now true
    tableRow.setColumn("in_archive", true);

    // Add suitable provenance - includes user, date, collections +
    // bitstream checksums
    prov.append(InstallItem.getBitstreamProvenanceMessage(this));

    addMetadata("dc", "description", "provenance", "en", prov.toString());

    // Update item in DB
    update();

    context.addContentEvent(this, EventType.REINSTATE);

    // authorization policies
    if (colls.size() > 0) {
        // FIXME: not multiple inclusion friendly - just apply access
        // policies from first collection
        // remove the item's policies and replace them with
        // the defaults from the collection
        inheritCollectionDefaultPolicies(colls.get(0));
    }

    // Write log
    log.info(LogManager.getHeader(context, "reinstate_item", "user=" + e.getEmail() + ",item_id=" + getID()));
}

From source file:org.dspace.eperson.Subscribe.java

License:BSD License

/**
 * Sends an email to the given e-person with details of new items in the
 * given collections, items that appeared yesterday. No e-mail is sent if
 * there aren't any new items in any of the collections.
 * //from   w  w w  .  j a v  a  2s.c o m
 * @param context
 *            DSpace context object
 * @param eperson
 *            eperson to send to
 * @param collections
 *            List of collection IDs (Integers)
 * @param test 
 */
public static void sendEmail(Context context, EPerson eperson, List<Collection> collections, boolean test)
        throws IOException, MessagingException, SQLException {
    // Get a resource bundle according to the eperson language preferences
    Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
    ResourceBundle labels = ResourceBundle.getBundle("Messages", supportedLocale);

    // Get the start and end dates for yesterday

    // The date should reflect the timezone as well. Otherwise we stand to lose that information 
    // in truncation and roll to an earlier date than intended.

    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String midnightYesterday = fmt.print(new DateMidnight(System.currentTimeMillis()));

    // FIXME: text of email should be more configurable from an
    // i18n viewpoint
    StringBuffer emailText = new StringBuffer();
    boolean isFirst = true;

    for (int i = 0; i < collections.size(); i++) {
        Collection c = collections.get(i);

        try {
            boolean includeAll = ConfigurationManager
                    .getBooleanProperty("harvest.includerestricted.subscription", true);

            // we harvest all the changed item from yesterday until now
            List<HarvestedItemInfo> itemInfos = Harvest.harvest(context, c, midnightYesterday, null, 0, // Limit
                    // and
                    // offset
                    // zero,
                    // get
                    // everything
                    0, true, // Need item objects
                    false, // But not containers
                    false, // Or withdrawals
                    includeAll);

            if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false)) {
                // get only the items archived yesterday
                itemInfos = filterOutModified(itemInfos);
            } else {
                // strip out the item archived today or 
                // not archived yesterday and modified today
                itemInfos = filterOutToday(itemInfos);
            }

            // Only add to buffer if there are new items
            if (itemInfos.size() > 0) {
                if (!isFirst) {
                    emailText.append("\n---------------------------------------\n");
                } else {
                    isFirst = false;
                }

                emailText.append(labels.getString("org.dspace.eperson.Subscribe.new-items")).append(" ")
                        .append(c.getMetadata("name")).append(": ").append(itemInfos.size()).append("\n\n");

                for (int j = 0; j < itemInfos.size(); j++) {
                    HarvestedItemInfo hii = (HarvestedItemInfo) itemInfos.get(j);

                    List<MDValue> titles = hii.item.getMetadata("dc", "title", null, MDValue.ANY);
                    emailText.append("      ").append(labels.getString("org.dspace.eperson.Subscribe.title"))
                            .append(" ");

                    if (titles.size() > 0) {
                        emailText.append(titles.get(0).getValue());
                    } else {
                        emailText.append(labels.getString("org.dspace.eperson.Subscribe.untitled"));
                    }

                    List<MDValue> authors = hii.item.getMetadata("dc", "contributor", MDValue.ANY, MDValue.ANY);

                    if (authors.size() > 0) {
                        emailText.append("\n    ")
                                .append(labels.getString("org.dspace.eperson.Subscribe.authors")).append(" ")
                                .append(authors.get(0).getValue());

                        for (int k = 1; k < authors.size(); k++) {
                            emailText.append("\n             ").append(authors.get(k).getValue());
                        }
                    }

                    emailText.append("\n         ").append(labels.getString("org.dspace.eperson.Subscribe.id"))
                            .append(" ").append(HandleManager.getCanonicalForm(hii.handle)).append("\n\n");
                }
            }
        } catch (ParseException pe) {
            // This should never get thrown as the Dates are auto-generated
        }
    }

    // Send an e-mail if there were any new items
    if (emailText.length() > 0) {

        if (test) {
            log.info(LogManager.getHeader(context, "subscription:", "eperson=" + eperson.getEmail()));
            log.info(LogManager.getHeader(context, "subscription:", "text=" + emailText.toString()));

        } else {

            Email email = Email.fromTemplate(context,
                    I18nUtil.getEmailFilename(supportedLocale, "subscription"));
            email.addRecipient(eperson.getEmail());
            email.addArgument(emailText.toString());
            email.send();

            log.info(LogManager.getHeader(context, "sent_subscription", "eperson_id=" + eperson.getID()));

        }
    }
}

From source file:org.elasticsearch.common.joda.Joda.java

License:Apache License

/**
 * Parses a joda based pattern, including some named ones (similar to the built in Joda ISO ones).
 *///ww w.ja  va 2 s .  co m
public static FormatDateTimeFormatter forPattern(String input, Locale locale) {
    if (Strings.hasLength(input)) {
        input = input.trim();
    }
    if (input == null || input.length() == 0) {
        throw new IllegalArgumentException("No date pattern provided");
    }

    DateTimeFormatter formatter;
    if ("basicDate".equals(input) || "basic_date".equals(input)) {
        formatter = ISODateTimeFormat.basicDate();
    } else if ("basicDateTime".equals(input) || "basic_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicDateTime();
    } else if ("basicDateTimeNoMillis".equals(input) || "basic_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicDateTimeNoMillis();
    } else if ("basicOrdinalDate".equals(input) || "basic_ordinal_date".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDate();
    } else if ("basicOrdinalDateTime".equals(input) || "basic_ordinal_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDateTime();
    } else if ("basicOrdinalDateTimeNoMillis".equals(input)
            || "basic_ordinal_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicOrdinalDateTimeNoMillis();
    } else if ("basicTime".equals(input) || "basic_time".equals(input)) {
        formatter = ISODateTimeFormat.basicTime();
    } else if ("basicTimeNoMillis".equals(input) || "basic_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicTimeNoMillis();
    } else if ("basicTTime".equals(input) || "basic_t_Time".equals(input)) {
        formatter = ISODateTimeFormat.basicTTime();
    } else if ("basicTTimeNoMillis".equals(input) || "basic_t_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicTTimeNoMillis();
    } else if ("basicWeekDate".equals(input) || "basic_week_date".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDate();
    } else if ("basicWeekDateTime".equals(input) || "basic_week_date_time".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDateTime();
    } else if ("basicWeekDateTimeNoMillis".equals(input) || "basic_week_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.basicWeekDateTimeNoMillis();
    } else if ("date".equals(input)) {
        formatter = ISODateTimeFormat.date();
    } else if ("dateHour".equals(input) || "date_hour".equals(input)) {
        formatter = ISODateTimeFormat.dateHour();
    } else if ("dateHourMinute".equals(input) || "date_hour_minute".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinute();
    } else if ("dateHourMinuteSecond".equals(input) || "date_hour_minute_second".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecond();
    } else if ("dateHourMinuteSecondFraction".equals(input)
            || "date_hour_minute_second_fraction".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecondFraction();
    } else if ("dateHourMinuteSecondMillis".equals(input) || "date_hour_minute_second_millis".equals(input)) {
        formatter = ISODateTimeFormat.dateHourMinuteSecondMillis();
    } else if ("dateOptionalTime".equals(input) || "date_optional_time".equals(input)) {
        // in this case, we have a separate parser and printer since the dataOptionalTimeParser can't print
        // this sucks we should use the root local by default and not be dependent on the node
        return new FormatDateTimeFormatter(input,
                ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC),
                ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC), locale);
    } else if ("dateTime".equals(input) || "date_time".equals(input)) {
        formatter = ISODateTimeFormat.dateTime();
    } else if ("dateTimeNoMillis".equals(input) || "date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.dateTimeNoMillis();
    } else if ("hour".equals(input)) {
        formatter = ISODateTimeFormat.hour();
    } else if ("hourMinute".equals(input) || "hour_minute".equals(input)) {
        formatter = ISODateTimeFormat.hourMinute();
    } else if ("hourMinuteSecond".equals(input) || "hour_minute_second".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecond();
    } else if ("hourMinuteSecondFraction".equals(input) || "hour_minute_second_fraction".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecondFraction();
    } else if ("hourMinuteSecondMillis".equals(input) || "hour_minute_second_millis".equals(input)) {
        formatter = ISODateTimeFormat.hourMinuteSecondMillis();
    } else if ("ordinalDate".equals(input) || "ordinal_date".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDate();
    } else if ("ordinalDateTime".equals(input) || "ordinal_date_time".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDateTime();
    } else if ("ordinalDateTimeNoMillis".equals(input) || "ordinal_date_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.ordinalDateTimeNoMillis();
    } else if ("time".equals(input)) {
        formatter = ISODateTimeFormat.time();
    } else if ("tTime".equals(input) || "t_time".equals(input)) {
        formatter = ISODateTimeFormat.tTime();
    } else if ("tTimeNoMillis".equals(input) || "t_time_no_millis".equals(input)) {
        formatter = ISODateTimeFormat.tTimeNoMillis();
    } else if ("weekDate".equals(input) || "week_date".equals(input)) {
        formatter = ISODateTimeFormat.weekDate();
    } else if ("weekDateTime".equals(input) || "week_date_time".equals(input)) {
        formatter = ISODateTimeFormat.weekDateTime();
    } else if ("weekyear".equals(input) || "week_year".equals(input)) {
        formatter = ISODateTimeFormat.weekyear();
    } else if ("weekyearWeek".equals(input)) {
        formatter = ISODateTimeFormat.weekyearWeek();
    } else if ("year".equals(input)) {
        formatter = ISODateTimeFormat.year();
    } else if ("yearMonth".equals(input) || "year_month".equals(input)) {
        formatter = ISODateTimeFormat.yearMonth();
    } else if ("yearMonthDay".equals(input) || "year_month_day".equals(input)) {
        formatter = ISODateTimeFormat.yearMonthDay();
    } else if (Strings.hasLength(input) && input.contains("||")) {
        String[] formats = Strings.delimitedListToStringArray(input, "||");
        DateTimeParser[] parsers = new DateTimeParser[formats.length];

        if (formats.length == 1) {
            formatter = forPattern(input, locale).parser();
        } else {
            DateTimeFormatter dateTimeFormatter = null;
            for (int i = 0; i < formats.length; i++) {
                DateTimeFormatter currentFormatter = forPattern(formats[i], locale).parser();
                if (dateTimeFormatter == null) {
                    dateTimeFormatter = currentFormatter;
                }
                parsers[i] = currentFormatter.getParser();
            }

            DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
                    .append(dateTimeFormatter.withZone(DateTimeZone.UTC).getPrinter(), parsers);
            formatter = builder.toFormatter();
        }
    } else {
        try {
            formatter = DateTimeFormat.forPattern(input);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid format: [" + input + "]: " + e.getMessage(), e);
        }
    }

    return new FormatDateTimeFormatter(input, formatter.withZone(DateTimeZone.UTC), locale);
}

From source file:org.elasticsearch.common.xcontent.BaseXContentTestCase.java

License:Apache License

public void testReadableInstant() throws Exception {
    assertResult("{'instant':null}",
            () -> builder().startObject().field("instant", (ReadableInstant) null).endObject());
    assertResult("{'instant':null}",
            () -> builder().startObject().field("instant").value((ReadableInstant) null).endObject());

    final DateTime t1 = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC);

    String expected = "{'t1':'2016-01-01T00:00:00.000Z'}";
    assertResult(expected, () -> builder().startObject().field("t1", t1).endObject());
    assertResult(expected, () -> builder().startObject().field("t1").value(t1).endObject());

    final DateTime t2 = new DateTime(2016, 12, 25, 7, 59, 42, 213, DateTimeZone.UTC);

    expected = "{'t2':'2016-12-25T07:59:42.213Z'}";
    assertResult(expected, () -> builder().startObject().field("t2", t2).endObject());
    assertResult(expected, () -> builder().startObject().field("t2").value(t2).endObject());

    final DateTimeFormatter formatter = randomFrom(ISODateTimeFormat.basicDate(),
            ISODateTimeFormat.dateTimeNoMillis());
    final DateTime t3 = DateTime.now();

    expected = "{'t3':'" + formatter.print(t3) + "'}";
    assertResult(expected, () -> builder().startObject().field("t3", t3, formatter).endObject());
    assertResult(expected, () -> builder().startObject().field("t3").value(t3, formatter).endObject());

    final DateTime t4 = new DateTime(randomDateTimeZone());

    expected = "{'t4':'" + formatter.print(t4) + "'}";
    assertResult(expected, () -> builder().startObject().field("t4", t4, formatter).endObject());
    assertResult(expected, () -> builder().startObject().field("t4").value(t4, formatter).endObject());

    long date = Math.abs(randomLong() % (2 * (long) 10e11)); // 1970-01-01T00:00:00Z - 2033-05-18T05:33:20.000+02:00
    final DateTime t5 = new DateTime(date, randomDateTimeZone());

    expected = "{'t5':'" + XContentBuilder.DEFAULT_DATE_PRINTER.print(t5) + "'}";
    assertResult(expected, () -> builder().startObject().field("t5", t5).endObject());
    assertResult(expected, () -> builder().startObject().field("t5").value(t5).endObject());

    expected = "{'t5':'" + formatter.print(t5) + "'}";
    assertResult(expected, () -> builder().startObject().field("t5", t5, formatter).endObject());
    assertResult(expected, () -> builder().startObject().field("t5").value(t5, formatter).endObject());

    Instant i1 = new Instant(1451606400000L); // 2016-01-01T00:00:00.000Z
    expected = "{'i1':'2016-01-01T00:00:00.000Z'}";
    assertResult(expected, () -> builder().startObject().field("i1", i1).endObject());
    assertResult(expected, () -> builder().startObject().field("i1").value(i1).endObject());

    Instant i2 = new Instant(1482652782213L); // 2016-12-25T07:59:42.213Z
    expected = "{'i2':'" + formatter.print(i2) + "'}";
    assertResult(expected, () -> builder().startObject().field("i2", i2, formatter).endObject());
    assertResult(expected, () -> builder().startObject().field("i2").value(i2, formatter).endObject());

    expectNonNullFormatterException(() -> builder().startObject().field("t3", t3, null).endObject());
    expectNonNullFormatterException(() -> builder().startObject().field("t3").value(t3, null).endObject());
}