Example usage for org.joda.time DateTime toString

List of usage examples for org.joda.time DateTime toString

Introduction

In this page you can find the example usage for org.joda.time DateTime toString.

Prototype

public String toString(String pattern) 

Source Link

Document

Output the instant using the specified format pattern.

Usage

From source file:JodaDT.java

License:Open Source License

/**
 * Converts a DateTimeObject into a string with format DD/MM/YYYY-hh:mm:ss.
 *
 * @param dt a DateTime object//from   w  w w .j  a v  a 2 s . co m
 * @return the formatted String or null
 */
public static String formatDDMMYYYYhhmmss(DateTime dt) {
    if (dt != null) {
        DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
        dtfb.appendDayOfMonth(2);
        dtfb.appendLiteral('/');
        dtfb.appendMonthOfYear(2);
        dtfb.appendLiteral('/');
        dtfb.appendYear(4, 4);
        dtfb.appendLiteral('-');
        dtfb.appendHourOfDay(2);
        dtfb.appendLiteral(':');
        dtfb.appendMinuteOfHour(2);
        dtfb.appendLiteral(':');
        dtfb.appendSecondOfMinute(2);
        DateTimeFormatter dtf = dtfb.toFormatter();
        String str = dt.toString(dtf);
        return str;
    } else {
        return null;
    }
}

From source file:JodaDT.java

License:Open Source License

/**
 * Converts a DateTimeObject into a string with format DD/MM/YYYY-hh:mm.
 *
 * @param dt a DateTime object//from   www . j  ava  2 s  . co m
 * @return the formatted String or null
 */
public static String formatDDMMYYYYhhmm(DateTime dt) {
    if (dt != null) {
        DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
        dtfb.appendDayOfMonth(2);
        dtfb.appendLiteral('/');
        dtfb.appendMonthOfYear(2);
        dtfb.appendLiteral('/');
        dtfb.appendYear(4, 4);
        dtfb.appendLiteral('-');
        dtfb.appendHourOfDay(2);
        dtfb.appendLiteral(':');
        dtfb.appendMinuteOfHour(2);
        DateTimeFormatter dtf = dtfb.toFormatter();
        String str = dt.toString(dtf);
        return str;
    } else {
        return null;
    }
}

From source file:JodaDT.java

License:Open Source License

/**
 * Converts a DateTimeObject into a string with format DD/MM/YYYY-hh.
 *
 * @param dt a DateTime object// w  w  w.  j  ava2 s  . c o m
 * @return the formatted String or null
 */
public static String formatDDMMYYYYhh(DateTime dt) {
    if (dt != null) {
        DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
        dtfb.appendDayOfMonth(2);
        dtfb.appendLiteral('/');
        dtfb.appendMonthOfYear(2);
        dtfb.appendLiteral('/');
        dtfb.appendYear(4, 4);
        dtfb.appendLiteral('-');
        dtfb.appendHourOfDay(2);
        DateTimeFormatter dtf = dtfb.toFormatter();
        String str = dt.toString(dtf);
        return str;
    } else {
        return null;
    }
}

From source file:JodaDT.java

License:Open Source License

/**
 * Converts a DateTimeObject into a string with format DD/MM/YYYY
 *
 * @param dt a DateTime object//  w  w  w  .ja  v a2s  .  c  om
 * @return the formatted String or null
 */
public static String formatDDMMYYYY(DateTime dt) {
    if (dt != null) {
        DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
        dtfb.appendDayOfMonth(2);
        dtfb.appendLiteral('/');
        dtfb.appendMonthOfYear(2);
        dtfb.appendLiteral('/');
        dtfb.appendYear(4, 4);
        DateTimeFormatter dtf = dtfb.toFormatter();
        String str = dt.toString(dtf);
        return str;
    } else {
        return null;
    }
}

From source file:JavaGlobal.java

License:Open Source License

private static void registerFormatters() {
    Formatters.register(DateTime.class, new Formatters.SimpleFormatter<DateTime>() {
        private final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); //ISO time without miliseconds

        @Override// www.  jav a 2  s  . c  o m
        public DateTime parse(String s, Locale locale) throws ParseException {
            return DATETIME_FORMATTER.parseDateTime(s);
        }

        @Override
        public String print(DateTime dateTime, Locale locale) {
            return dateTime.toString(DATETIME_FORMATTER);
        }
    });

    Formatters.register(Instant.class, new Formatters.SimpleFormatter<Instant>() {

        @Override
        public Instant parse(String s, Locale locale) throws ParseException {
            return Utils.toInstant(s);
        }

        @Override
        public String print(Instant instant, Locale locale) {
            // ignores locale!
            return Utils.toString(instant);
        }
    });

    Formatters.register(LocalDateTime.class, new Formatters.SimpleFormatter<LocalDateTime>() {

        @Override
        public LocalDateTime parse(String s, Locale locale) throws ParseException {
            return Utils.toLocalDateTime(s);
        }

        @Override
        public String print(LocalDateTime dateTime, Locale locale) {
            // ignores locale!
            return Utils.toString(dateTime);
        }
    });

    Formatters.register(LocalDate.class, new Formatters.SimpleFormatter<LocalDate>() {

        @Override
        public LocalDate parse(String s, Locale locale) throws ParseException {
            return Utils.toLocalDate(s);
        }

        @Override
        public String print(LocalDate localDate, Locale locale) {
            // ignores locale!
            return Utils.toDateString(localDate); // happens to be the correct format
        }
    });

    Formatters.register(EurocentAmount.class, new Formatters.SimpleFormatter<EurocentAmount>() {
        @Override
        public EurocentAmount parse(String s, Locale locale) throws ParseException {
            return EurocentAmount.parse(s);
        }

        @Override
        public String print(EurocentAmount eurocentAmount, Locale locale) {
            return eurocentAmount.toString();
        }
    });
}

From source file:adwords.axis.v201409.remarketing.AddRuleBasedUserLists.java

License:Open Source License

public static void runExample(AdWordsServices adWordsServices, AdWordsSession session) throws Exception {

    // Get the AdwordsUserListService.
    AdwordsUserListServiceInterface userListService = adWordsServices.get(session,
            AdwordsUserListServiceInterface.class);

    // First rule item group - users who visited the checkout page and had more than one item
    // in their shopping cart.
    StringKey pageTypeKey = new StringKey("ecomm_pagetype");

    StringRuleItem checkoutStringRuleItem = new StringRuleItem();
    checkoutStringRuleItem.setKey(pageTypeKey);
    checkoutStringRuleItem.setOp(StringRuleItemStringOperator.EQUALS);
    checkoutStringRuleItem.setValue("checkout");

    RuleItem checkoutRuleItem = new RuleItem();
    checkoutRuleItem.setStringRuleItem(checkoutStringRuleItem);

    NumberKey cartSizeKey = new NumberKey("cartsize");

    NumberRuleItem cartSizeNumberRuleItem = new NumberRuleItem();
    cartSizeNumberRuleItem.setKey(cartSizeKey);
    cartSizeNumberRuleItem.setOp(NumberRuleItemNumberOperator.GREATER_THAN);
    cartSizeNumberRuleItem.setValue(1.0);

    RuleItem cartSizeRuleItem = new RuleItem();
    cartSizeRuleItem.setNumberRuleItem(cartSizeNumberRuleItem);

    // Combine the two rule items into a RuleItemGroup so AdWords will AND their rules
    // together.//from   ww  w  .j  a  va2 s .c o  m
    RuleItemGroup checkoutMultipleItemGroup = new RuleItemGroup();
    checkoutMultipleItemGroup.setItems(new RuleItem[] { checkoutRuleItem, cartSizeRuleItem });

    // Second rule item group - users who checked out within the next 3 months.
    DateKey checkoutDateKey = new DateKey("checkoutdate");

    DateRuleItem startDateDateRuleItem = new DateRuleItem();
    startDateDateRuleItem.setKey(checkoutDateKey);
    startDateDateRuleItem.setOp(DateRuleItemDateOperator.AFTER);
    startDateDateRuleItem.setValue(new DateTime().toString(DATE_FORMAT_STRING));

    RuleItem startDateRuleItem = new RuleItem();
    startDateRuleItem.setDateRuleItem(startDateDateRuleItem);

    DateRuleItem endDateDateRuleItem = new DateRuleItem();
    endDateDateRuleItem.setKey(checkoutDateKey);
    endDateDateRuleItem.setOp(DateRuleItemDateOperator.BEFORE);
    endDateDateRuleItem.setValue(new DateTime().plusMonths(3).toString(DATE_FORMAT_STRING));

    RuleItem endDateRuleItem = new RuleItem();
    endDateRuleItem.setDateRuleItem(endDateDateRuleItem);

    // Combine the date rule items into a RuleItemGroup.
    RuleItemGroup checkedOutNextThreeMonthsItemGroup = new RuleItemGroup();
    checkedOutNextThreeMonthsItemGroup.setItems(new RuleItem[] { startDateRuleItem, endDateRuleItem });

    // Combine the rule item groups into a Rule so AdWords will OR the groups together.
    Rule rule = new Rule();
    rule.setGroups(new RuleItemGroup[] { checkoutMultipleItemGroup, checkedOutNextThreeMonthsItemGroup });

    // Create the user list with no restrictions on site visit date.
    ExpressionRuleUserList expressionUserList = new ExpressionRuleUserList();
    expressionUserList
            .setName("Expression based user list created at " + new DateTime().toString("yyyyMMdd_HHmmss"));
    expressionUserList
            .setDescription("Users who checked out in three month window OR visited the checkout page "
                    + "with more than one item in their cart");
    expressionUserList.setRule(rule);

    // Create the user list restricted to users who visit your site within the next six months.
    DateTime startDate = new DateTime();
    DateTime endDate = startDate.plusMonths(6);

    DateSpecificRuleUserList dateUserList = new DateSpecificRuleUserList();
    dateUserList.setName("Date rule user list created at " + new DateTime().toString("yyyyMMdd_HHmmss"));
    dateUserList.setDescription(String.format(
            "Users who visited the site between %s and %s and "
                    + "checked out in three month window OR visited the checkout page "
                    + "with more than one item in their cart",
            startDate.toString(DATE_FORMAT_STRING), endDate.toString(DATE_FORMAT_STRING)));
    dateUserList.setRule(rule);

    // Set the start and end dates of the user list.
    dateUserList.setStartDate(startDate.toString(DATE_FORMAT_STRING));
    dateUserList.setEndDate(endDate.toString(DATE_FORMAT_STRING));

    // Create operations to add the user lists.
    List<UserListOperation> operations = Lists.newArrayList();
    for (UserList userList : new UserList[] { expressionUserList, dateUserList }) {
        UserListOperation operation = new UserListOperation();
        operation.setOperand(userList);
        operation.setOperator(Operator.ADD);
        operations.add(operation);
    }

    // Submit the operations.
    UserListReturnValue result = userListService
            .mutate(operations.toArray(new UserListOperation[operations.size()]));

    // Display the results.
    for (UserList userListResult : result.getValue()) {
        System.out.printf(
                "User list added with ID %d, name '%s', status '%s', list type '%s',"
                        + " accountUserListStatus '%s', description '%s'.%n",
                userListResult.getId(), userListResult.getName(), userListResult.getStatus().getValue(),
                userListResult.getListType() == null ? null : userListResult.getListType().getValue(),
                userListResult.getAccountUserListStatus().getValue(), userListResult.getDescription());
    }
}

From source file:adwords.axis.v201502.advancedoperations.AddAdCustomizer.java

License:Open Source License

/**
 * Creates FeedItems with the values to use in ad customizations for each ad group in
 * <code>adGroupIds</code>./*from w  w w .  ja v  a2s  .c o m*/
 */
private static void createCustomizerFeedItems(AdWordsServices adWordsServices, AdWordsSession session,
        List<Long> adGroupIds, AdCustomizerFeed adCustomizerFeed) throws Exception {
    // Get the FeedItemService.
    FeedItemServiceInterface feedItemService = adWordsServices.get(session, FeedItemServiceInterface.class);

    List<FeedItemOperation> feedItemOperations = Lists.newArrayList();

    DateTime now = new DateTime();

    DateTime marsDate = new DateTime(now.getYear(), now.getMonthOfYear(), 1, 0, 0);
    feedItemOperations.add(createFeedItemAddOperation("Mars", "$1234.56", marsDate.toString("yyyyMMdd HHmmss"),
            adGroupIds.get(0), adCustomizerFeed));

    DateTime venusDate = new DateTime(now.getYear(), now.getMonthOfYear(), 15, 0, 0);
    feedItemOperations.add(createFeedItemAddOperation("Venus", "$1450.00",
            venusDate.toString("yyyyMMdd HHmmss"), adGroupIds.get(1), adCustomizerFeed));

    FeedItemReturnValue feedItemReturnValue = feedItemService
            .mutate(feedItemOperations.toArray(new FeedItemOperation[feedItemOperations.size()]));

    for (FeedItem addedFeedItem : feedItemReturnValue.getValue()) {
        System.out.printf("Added feed item with ID %d.%n", addedFeedItem.getFeedItemId());
    }
}

From source file:adwords.axis.v201502.extensions.AddSiteLinks.java

License:Open Source License

public static void runExample(AdWordsServices adWordsServices, AdWordsSession session, Long campaignId)
        throws ApiException, RemoteException {
    // Get the CustomerService.
    CustomerServiceInterface customerService = adWordsServices.get(session, CustomerServiceInterface.class);
    Customer customer = customerService.get();
    DateTimeZone customerTimeZone = DateTimeZone.forID(customer.getDateTimeZone());

    // Get the CampaignExtensionSettingService.
    CampaignExtensionSettingServiceInterface campaignExtensionSettingService = adWordsServices.get(session,
            CampaignExtensionSettingServiceInterface.class);

    // Create the sitelinks.
    SitelinkFeedItem sitelink1 = createSiteLinkFeedItem("Store Hours", "http://www.example.com/storehours");

    // Show the Thanksgiving specials link only from 20 - 27 Nov.
    SitelinkFeedItem sitelink2 = createSiteLinkFeedItem("Thanksgiving Specials",
            "http://www.example.com/thanksgiving");

    // The time zone of the start and end date/times must match the time zone of the customer.
    DateTime startTime = new DateTime(DateTime.now().getYear(), 11, 20, 0, 0, 0, customerTimeZone);
    sitelink2.setStartTime(startTime.toString("yyyyMMdd HHmmss ZZZ"));
    DateTime endTime = new DateTime(DateTime.now().getYear(), 11, 27, 23, 59, 59, customerTimeZone);
    sitelink2.setEndTime(endTime.toString("yyyyMMdd HHmmss ZZZ"));

    // Show the wifi details primarily for high end mobile users.
    SitelinkFeedItem sitelink3 = createSiteLinkFeedItem("Wifi available", "http://www.example.com/mobile/wifi");
    // See https://developers.google.com/adwords/api/docs/appendix/platforms for device criteria
    // IDs./*from  www  .  ja  v a  2 s  .co m*/
    FeedItemDevicePreference devicePreference = new FeedItemDevicePreference(30001L);
    sitelink3.setDevicePreference(devicePreference);

    // Show the happy hours link only during Mon - Fri 6PM to 9PM.
    SitelinkFeedItem sitelink4 = createSiteLinkFeedItem("Happy hours", "http://www.example.com/happyhours");
    sitelink4.setScheduling(new FeedItemScheduling(new FeedItemSchedule[] {
            new FeedItemSchedule(DayOfWeek.MONDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.TUESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.WEDNESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.THURSDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.FRIDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO) }));

    // Create your campaign extension settings. This associates the sitelinks
    // to your campaign.
    CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting();
    campaignExtensionSetting.setCampaignId(campaignId);
    campaignExtensionSetting.setExtensionType(FeedType.SITELINK);
    ExtensionSetting extensionSetting = new ExtensionSetting();
    extensionSetting.setExtensions(new ExtensionFeedItem[] { sitelink1, sitelink2, sitelink3, sitelink4 });
    campaignExtensionSetting.setExtensionSetting(extensionSetting);

    CampaignExtensionSettingOperation operation = new CampaignExtensionSettingOperation();
    operation.setOperand(campaignExtensionSetting);
    operation.setOperator(Operator.ADD);

    // Add the extensions.
    CampaignExtensionSettingReturnValue returnValue = campaignExtensionSettingService
            .mutate(new CampaignExtensionSettingOperation[] { operation });
    if (returnValue.getValue() != null && returnValue.getValue().length > 0) {
        CampaignExtensionSetting newExtensionSetting = returnValue.getValue(0);
        System.out.printf("Extension setting with type = %s was added to campaign ID %d.%n",
                newExtensionSetting.getExtensionType().getValue(), newExtensionSetting.getCampaignId());
    } else {
        System.out.println("No extension settings were created.");
    }
}

From source file:am.ik.categolj2.infra.search.DateTimeBridge.java

License:Apache License

@Override
public String objectToString(Object object) {
    DateTime datetime = (DateTime) object;
    String date = datetime.toString("yyyy-MM-dd");
    return date;//from w  w  w. j  a  v a 2 s . c  om
}

From source file:aplicacion.control.util.Fechas.java

public static String getFechaConMesYHora(DateTime dateTime) {
    String fecha = dateTime.getDayOfMonth() + " de " + getMonthName(dateTime.getMonthOfYear()) + " "
            + dateTime.getYear() + " a las " + dateTime.toString("HH:mm:ss");
    return fecha;
}