Java Examples for org.joda.time.format.DateTimeFormat

The following java examples will help you to understand the usage of org.joda.time.format.DateTimeFormat. These source code samples are taken from different open source projects.

Example 1
Project: cms-ce-master  File: NonRepeatableSyncValueResolver.java View source code
String resolve(String syncValue) {
    StringBuilder s = new StringBuilder();
    s.append(syncValue);
    s.append("_nonRepeatable_");
    DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss");
    s.append(timeService.getNowAsDateTime().toString(formatter));
    s.append("_");
    s.append(secureRandom.nextInt());
    return s.toString();
}
Example 2
Project: longneck-core-master  File: DateTimeToMillisecondsTest.java View source code
@Test
public void testConversion() {
    String input = "21/Jan/2012:02:34:42 +0100";
    String pattern = "dd/MMM/yyyy:HH:mm:ss Z";
    DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
    DateTime actual = dtf.parseDateTime(input);
    DateTime expected = new DateTime(2012, 1, 21, 2, 34, 42, DateTimeZone.forOffsetHours(1));
    Assert.assertTrue(expected.isEqual(actual));
}
Example 3
Project: quartz-glass-master  File: DayOfWeekDescriptionBuilder.java View source code
@Override
protected String getSingleItemDescription(String expression) {
    String exp = expression;
    if (expression.contains("#")) {
        exp = expression.substring(0, expression.indexOf("#"));
    } else if (expression.contains("L")) {
        exp = exp.replace("L", "");
    }
    if (StringUtils.isNumeric(exp)) {
        return DateAndTimeUtils.getDayOfWeekName(Integer.parseInt(exp));
    } else {
        return DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH).parseDateTime(WordUtils.capitalizeFully(exp)).dayOfWeek().getAsText(Locale.ENGLISH);
    }
}
Example 4
Project: Rythm-master  File: JodaDateTimeFormatter.java View source code
@Override
public String format(Object val, String pattern, Locale locale, String timezone) {
    if (!(val instanceof DateTime))
        return null;
    DateTimeFormatter fmt;
    if (null != pattern)
        fmt = DateTimeFormat.forPattern(pattern);
    else
        fmt = DateTimeFormat.fullDateTime();
    fmt = fmt.withLocale(locale);
    if (null != timezone) {
        DateTimeZone dtz = DateTimeZone.forID(timezone);
        fmt = fmt.withZone(dtz);
    }
    return fmt.print((DateTime) val);
}
Example 5
Project: rythmengine-master  File: JodaDateTimeFormatter.java View source code
@Override
public String format(Object val, String pattern, Locale locale, String timezone) {
    if (!(val instanceof DateTime))
        return null;
    DateTimeFormatter fmt;
    if (null != pattern)
        fmt = DateTimeFormat.forPattern(pattern);
    else
        fmt = DateTimeFormat.fullDateTime();
    fmt = fmt.withLocale(locale);
    if (null != timezone) {
        DateTimeZone dtz = DateTimeZone.forID(timezone);
        fmt = fmt.withZone(dtz);
    }
    return fmt.print((DateTime) val);
}
Example 6
Project: scene-master  File: DeactivateSituationEvent.java View source code
public String toString() {
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy MM dd HH:mm:ss");
    DateTime activation = new DateTime(this.getSituation().getActivation().getTimestamp());
    DateTime deactivation = new DateTime(this.getTimestamp());
    Period period = new Period(activation, deactivation);
    StringBuilder str = new StringBuilder();
    str.append("\tDeactivation timestamp: ");
    str.append(deactivation.toString(fmt));
    str.append(". Duration: ");
    str.append(period.getDays());
    str.append(" days ");
    str.append(period.getHours());
    str.append(" hours ");
    str.append(period.getMinutes());
    str.append(" minutes ");
    str.append(period.getSeconds());
    str.append(" seconds.");
    return str.toString();
}
Example 7
Project: hadoop-pig-master  File: CustomFormatToISO.java View source code
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 2) {
        return null;
    }
    // Set the time to default or the output is in UTC
    DateTimeZone.setDefault(DateTimeZone.UTC);
    String date = input.get(0).toString();
    String format = input.get(1).toString();
    // See http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormat.html
    DateTimeFormatter parser = DateTimeFormat.forPattern(format);
    DateTime result = parser.parseDateTime(date);
    return result.toString();
}
Example 8
Project: pig-master  File: ToDate3ARGS.java View source code
public DateTime exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTimeFormatter dtf = DateTimeFormat.forPattern(DataType.toString(input.get(1)));
    DateTimeZone dtz = DateTimeZone.forOffsetMillis(DateTimeZone.forID(DataType.toString(input.get(2))).getOffset(null));
    return dtf.withZone(dtz).parseDateTime(DataType.toString(input.get(0)));
}
Example 9
Project: spork-master  File: ToDate3ARGS.java View source code
public DateTime exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    DateTimeFormatter dtf = DateTimeFormat.forPattern(DataType.toString(input.get(1)));
    DateTimeZone dtz = DateTimeZone.forOffsetMillis(DateTimeZone.forID(DataType.toString(input.get(2))).getOffset(null));
    return dtf.withZone(dtz).parseDateTime(DataType.toString(input.get(0)));
}
Example 10
Project: cryptosms-master  File: UtilsTextFormat.java View source code
/**
	 * Format date time.
	 *
	 * @param timeStamp the time stamp
	 * @return the string
	 */
public static String formatDateTime(DateTime timeStamp) {
    DateTime now = DateTime.now();
    if (timeStamp.toLocalDate().equals(now.toLocalDate()))
        // today => just time
        return timeStamp.toString(DateTimeFormat.shortTime());
    else
        // not today => just date
        return timeStamp.toString(DateTimeFormat.shortDate());
}
Example 11
Project: Java-library-master  File: PushInfoResponseTest.java View source code
@Test
public void testPushInfoResponseBuilder() {
    UUID one = UUID.randomUUID();
    UUID two = UUID.randomUUID();
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime dt = formatter.parseDateTime("2013-07-31 21:27:38");
    PushInfoResponse obj = PushInfoResponse.newBuilder().setPushId(one).setDirectResponses(4).setSends(5).setPushType(PushInfoResponse.PushType.UNICAST_PUSH).setPushTime("2013-07-31 21:27:38").setGroupId(two).build();
    assertNotNull(obj);
    assertEquals(one, obj.getPushId());
    assertEquals(4, obj.getDirectResponses());
    assertEquals(5, obj.getSends());
    assertEquals(PushInfoResponse.PushType.UNICAST_PUSH, obj.getPushType());
    assertEquals(dt, obj.getPushTime());
    assertTrue(obj.getGroupID().isPresent());
    assertEquals(two, obj.getGroupID().get());
}
Example 12
Project: yeslib-master  File: JodaDateTimeConverterUtilTest.java View source code
@Test
public void testFromString() {
    DateTimeFormatter formatter = DateTimeFormat.fullDate();
    DateTime dt = new DateTime(8238923L);
    String s = dt.toString(formatter);
    JodaDateTimeConverter converter = new JodaDateTimeConverter(formatter);
    DateTime result = (DateTime) converter.fromString(s);
    assertEquals(dt.getYear(), result.getYear());
    assertEquals(dt.getMonthOfYear(), result.getMonthOfYear());
    assertEquals(dt.getDayOfYear(), result.getDayOfYear());
}
Example 13
Project: flare-spork-master  File: ToString.java View source code
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    if (input.size() == 1) {
        return DataType.toDateTime(input.get(0)).toString();
    } else if (input.size() == 2) {
        DateTimeFormatter dtf = DateTimeFormat.forPattern(DataType.toString(input.get(1)));
        return DataType.toDateTime(input.get(0)).toString(dtf);
    } else {
        return null;
    }
}
Example 14
Project: spork-streaming-master  File: ToString.java View source code
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 1 || input.get(0) == null) {
        return null;
    }
    if (input.size() == 1) {
        return DataType.toDateTime(input.get(0)).toString();
    } else if (input.size() == 2) {
        DateTimeFormatter dtf = DateTimeFormat.forPattern(DataType.toString(input.get(1)));
        return DataType.toDateTime(input.get(0)).toString(dtf);
    } else {
        return null;
    }
}
Example 15
Project: bacon-master  File: ParseTimestamp.java View source code
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() == 0)
        return null;
    try {
        String date = (String) input.get(0);
        int len = date.length();
        String format = null;
        if (len == 12)
            format = "YYYYMMddHHmm";
        if (len == 14)
            format = "YYYYMMddHHmmss";
        if (len == 20)
            format = "YYYY-MM-dd'T'HH:mm:ss'Z'";
        // Unknown format.
        if (format == null)
            return null;
        // Set the time to default or the output is in UTC
        DateTimeZone.setDefault(DateTimeZone.UTC);
        // See http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormat.html
        DateTimeFormatter parser = DateTimeFormat.forPattern(format);
        DateTime result = parser.parseDateTime(date);
        return result.toString();
    } catch (Exception e) {
        return null;
    }
}
Example 16
Project: brickhouse-master  File: AddISOPeriodUDF.java View source code
public String evaluate(String dateString, String dateFormat, String periodString) {
    if (dateString == null) {
        return null;
    }
    if (dateFormat == null) {
        dateFormat = "YYYY-MM-dd HH:mm:ss";
    }
    DateTimeFormatter dateFormatter = org.joda.time.format.DateTimeFormat.forPattern(dateFormat);
    DateTime input = dateFormatter.parseDateTime(dateString);
    Duration duration = periodFormatter.parsePeriod(periodString).toStandardDuration();
    long seconds = duration.getStandardSeconds();
    DateTime output = input.plusSeconds(Long.valueOf(seconds).intValue());
    return dateFormatter.print(output);
}
Example 17
Project: btpka3.github.com-master  File: HelloServlet.java View source code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String now = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss.SSS Z").print(DateTime.now());
    String user = request.getParameter("user");
    if (StringUtils.isBlank(user)) {
        user = "Guset";
    }
    PrintWriter out = response.getWriter();
    out.write(String.format("%s : Hello %s", now, user));
    out.flush();
}
Example 18
Project: compass-fork-master  File: DataTimeConverter.java View source code
public Formatter create() {
    if (ISO.equalsIgnoreCase(format)) {
        return new DateTimeFormatter(ISODateTimeFormat.dateTime());
    }
    org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
    formatter = formatter.withLocale(locale);
    return new DateTimeFormatter(formatter);
}
Example 19
Project: constellio-master  File: BaseDateField.java View source code
private static Date parseBidirectionallyDateString(final String dateString, final String dateFormat) {
    try {
        return LocalDate.parse(dateString, DateTimeFormat.forPattern(dateFormat)).toDate();
    } catch (final IllegalArgumentException e1) {
        try {
            final String reversedDateFormat = new StringBuilder(dateFormat).reverse().toString();
            return LocalDate.parse(dateString, DateTimeFormat.forPattern(reversedDateFormat)).toDate();
        } catch (final IllegalArgumentException e2) {
            throw new ConversionException(e2.getLocalizedMessage());
        }
    }
}
Example 20
Project: evercam-play-android-master  File: TimeCounter.java View source code
@Override
public void run() {
    //	    		Date now = new Date(System.currentTimeMillis());
    //	    		SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy
    // HH:mm:ss");
    //	    		String timeString = formatter.format(now);
    //	    		timeTextView.setText(timeString);
    org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID(timezone);
    org.joda.time.DateTime dateTime = new org.joda.time.DateTime(timeZone);
    org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
    String timeAsString = dateTime.toString(formatter);
    timeTextView.setText(timeAsString);
}
Example 21
Project: falcon-master  File: SchedulerUtilTest.java View source code
@DataProvider(name = "frequencies")
public Object[][] getTestFrequencies() {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss x");
    return new Object[][] { { DateTime.now(), new Frequency("minutes(10)"), 10 * 60 * 1000L }, { DateTime.now(), new Frequency("hours(6)"), 6 * 60 * 60 * 1000L }, // Feb of leap year
    { formatter.parseDateTime("04/02/2012 14:00:00 -0800"), new Frequency("months(1)"), 29 * 24 * 60 * 60 * 1000L }, // Months with 31 and 30 days
    { formatter.parseDateTime("02/10/2015 03:30:00 +0530"), new Frequency("months(2)"), (31 + 30) * 24 * 60 * 60 * 1000L } };
}
Example 22
Project: fenixedu-academic-master  File: GroupingJsonAdapter.java View source code
@Override
public JsonElement view(Grouping grouping, JsonBuilder ctx) {
    JsonObject object = new JsonObject();
    DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm dd/MM/yyyy");
    object.addProperty("externalId", grouping.getExternalId());
    object.addProperty("name", grouping.getName());
    object.addProperty("description", grouping.getProjectDescription());
    object.addProperty("enrolmentBeginDay", grouping.getEnrolmentBeginDayDateDateTime().getMillis());
    object.addProperty("enrolmentEndDay", grouping.getEnrolmentEndDayDateDateTime().getMillis());
    object.addProperty("shiftType", grouping.getShiftType() == null ? "" : grouping.getShiftType().toString());
    object.addProperty("atomicEnrolmentPolicy", grouping.getEnrolmentPolicy().getType() == EnrolmentGroupPolicyType.ATOMIC);
    object.addProperty("differentiatedCapacity", grouping.getDifferentiatedCapacity());
    object.addProperty("minimumGroupCapacity", grouping.getMinimumCapacity());
    object.addProperty("maximumGroupCapacity", grouping.getMaximumCapacity());
    object.addProperty("idealGroupCapacity", grouping.getIdealCapacity());
    object.addProperty("maxGroupNumber", grouping.getGroupMaximumNumber());
    JsonUtils.put(object, "executionCourses", ctx.view(grouping.getExecutionCourses()));
    return object;
}
Example 23
Project: flume-master  File: TestRegexExtractorInterceptorMillisSerializer.java View source code
@Test
public void shouldReturnMillisFromPattern() {
    RegexExtractorInterceptorMillisSerializer fixture = new RegexExtractorInterceptorMillisSerializer();
    Context context = new Context();
    String pattern = "yyyy-MM-dd HH:mm:ss";
    context.put("pattern", pattern);
    fixture.configure(context);
    DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
    long time = (System.currentTimeMillis() / 1000L) * 1000L;
    Assert.assertEquals(String.valueOf(time), fixture.serialize(formatter.print(time)));
}
Example 24
Project: frisbee-master  File: GdgDashClockExtension.java View source code
@Override
public void onSuccess(PagedList<Event> eventsPagedList) {
    List<Event> events = eventsPagedList.getItems();
    if (events.size() > 0) {
        if (events.get(0).getGPlusEventLink() != null) {
            Event event = events.get(0);
            String expandedBody = event.getStart().toLocalDateTime().toString(DateTimeFormat.patternForStyle("MS", Locale.getDefault()));
            publishUpdate(new ExtensionData().visible(true).icon(R.drawable.ic_dashclock).status("GDG").expandedTitle(event.getTitle()).expandedBody(expandedBody).clickIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(event.getGPlusEventLink()))));
        }
    } else {
        publishUpdate(new ExtensionData().visible(false));
    }
}
Example 25
Project: Gitskarios-master  File: IssueStoryLabelDetailView.java View source code
private void printLabelsEvent(boolean added, long created_at, User user, List<Label> labels) {
    userText.setText(user.getLogin());
    profileIcon.setUser(user);
    labelsView.setLabels(labels);
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String date = TimeUtils.getTimeAgoString(formatter.print(created_at));
    String dateText = getContext().getResources().getString(added ? R.string.aissue_detail_add_labels : R.string.aissue_detail_removed_labels, date);
    createdAt.setText(dateText);
}
Example 26
Project: gocd-master  File: ChangeSetXML.java View source code
public static ChangeSetXML[] changesetXMLs(int from, int to) {
    ArrayList<ChangeSetXML> result = new ArrayList<>();
    for (int rev = from; rev <= to; rev++) {
        String time = new DateTime(3600 * rev * 1000).toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss Z"));
        result.add(changesetXML("http://changeset/revision-" + rev).message("message " + rev).revision("" + rev).user("user" + rev).time(time));
    }
    return result.toArray(new ChangeSetXML[] {});
}
Example 27
Project: google-maps-services-java-master  File: LocalTimeAdapter.java View source code
/**
   * Read a time from the Places API and convert to a {@link LocalTime}
   */
@Override
public LocalTime read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }
    if (reader.peek() == JsonToken.STRING) {
        DateTimeFormatter dtf = DateTimeFormat.forPattern("HHmm");
        return LocalTime.parse(reader.nextString(), dtf);
    }
    throw new UnsupportedOperationException("Unsupported format");
}
Example 28
Project: head-master  File: DateFormatter.java View source code
/**
     * @param args
     *            a list of arguments passed in from FTL in this order:
     *            <ul>
     *            <li>date object to be formatted. It can be an instance of either java.util.Date,
     *            org.joda.time.DateTime or org.joda.time.LocalDate</li>
     *            <li>pattern: date format pattern see {@link java.text.SimpleDateFormat}</li>
     *            <li>locale: an instance of java.util.Locale</li>
     *            </ul>
     */
@Override
public Object exec(List args) throws TemplateModelException {
    if (args.size() != 3) {
        throw new IllegalArgumentException("Wrong arguments");
    }
    Object date = DeepUnwrap.unwrap((TemplateModel) args.get(0));
    String pattern = (String) DeepUnwrap.unwrap((TemplateModel) args.get(1));
    Locale locale = (Locale) DeepUnwrap.unwrap((TemplateModel) args.get(2));
    if (date instanceof LocalDate) {
        date = ((LocalDate) date).toDateTimeAtStartOfDay();
    }
    String formatted = "";
    if (date instanceof DateTime) {
        formatted = DateTimeFormat.forPattern(pattern).withLocale(locale).print((DateTime) date);
    } else if (date instanceof Date) {
        formatted = new SimpleDateFormat(pattern, locale).format((Date) date);
    } else if (date != null) {
        throw new IllegalArgumentException("Unsupported date type: " + date.getClass());
    }
    return formatted;
}
Example 29
Project: helper-android-master  File: ScheduleManager.java View source code
public boolean isLessonsEndToday(String groupId, int subgroup) {
    DateTime currentTime = new DateTime();
    Lesson[] lessons = mScheduleDatabase.getLessonsOfDay(groupId, DateTime.now(), subgroup);
    if (lessons.length > 0) {
        Lesson lesson = lessons[lessons.length - 1];
        DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
        DateTime dt = formatter.parseDateTime(getFinishTimeOfLesson(lesson));
        if (currentTime.getHourOfDay() + 1 > dt.getHourOfDay()) {
            return true;
        }
    } else {
        return true;
    }
    return false;
}
Example 30
Project: humanize-master  File: TestJodaTime.java View source code
@Test
public void dateFormat() {
    DateTime zero = new DateTime(0).millisOfDay().setCopy(0).secondOfDay().setCopy(0);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    // Assert.assertEquals(zero.toString(fmt),
    // "1970-01-01T00:00:00.000+01:00");
    fmt = ISODateTimeFormat.basicDate();
    Assert.assertEquals(zero.toString(fmt), "19700101");
    fmt = ISODateTimeFormat.basicOrdinalDate();
    Assert.assertEquals(zero.toString(fmt), "1970001");
    fmt = DateTimeFormat.fullDate().withLocale(Locale.ENGLISH);
    Assert.assertEquals(zero.toString(fmt), "Thursday, January 1, 1970");
}
Example 31
Project: hydra-master  File: TestDateUtil.java View source code
@Test
public void withFormatter() {
    DateTimeFormatter format = DateTimeFormat.forPattern("yyyyww");
    String expanded = DateUtil.expandDateMacro("{{now::yyyyww}}/{{now-1::yyyyww}},{{now::yyyyww}},123442/{{now, {{now::yyyyww}}");
    String now = DateUtil.getDateTime(format, "{{now}}").toString(format);
    String nowMinus1 = DateUtil.getDateTime(format, "{{now-1}}").toString(format);
    assertEquals(String.format("%s/%s,%s,123442/{{now, %s", now, nowMinus1, now, now), expanded);
}
Example 32
Project: jcommune-master  File: DateTimeEditor.java View source code
@Override
public void setAsText(String text) {
    if (text != null && !text.isEmpty()) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(this.format);
        try {
            setValue(dateTimeFormatter.parseDateTime(text));
        } catch (IllegalArgumentException e) {
            setValue(null);
        }
    }
}
Example 33
Project: JECommons-master  File: JEVisImporterAdapter.java View source code
private static void setLastReadout(JEVisObject channel, DateTime lastDateTime) {
    try {
        String toString = lastDateTime.toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        JEVisSample buildSample = channel.getAttribute(DataCollectorTypes.Channel.LAST_READOUT).buildSample(new DateTime(), toString);
        buildSample.commit();
    } catch (JEVisException ex) {
        java.util.logging.Logger.getLogger(DataSourceHelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
}
Example 34
Project: JHydra-master  File: NonFatalExitTestCaseResultTests.java View source code
@Test
public void nonFatalExitTestCaseResult_getRunStartTime_correctDateTime() {
    final NonFatalExitTestCaseResult testCaseResult = getNonFatalExitTestResult();
    final String expected = "09-Mar-13 08.50.10 AM";
    final String dateTimePattern = "dd-MMM-yy hh.mm.ss aa";
    final String actual = testCaseResult.getRunStartTime().toString(DateTimeFormat.forPattern(dateTimePattern));
    Assert.assertEquals(expected, actual);
}
Example 35
Project: jirrigate-master  File: IrrigationResult.java View source code
@Override
public String toString() {
    String result = "";
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
    result += "Start: " + new DateTime(startTime).toString(formatter);
    result += "\nEnd: " + new DateTime(endTime).toString(formatter);
    result += "\nDuration: " + (((endTime - startTime) / 1000) / 60) + "m";
    result += "\nZones: ";
    for (Zone z : zones) {
        result += z.getName() + ",";
    }
    result += "\nResult: " + this.result;
    result += "\nCommand Sent: " + commandSent;
    result += "\nMessage: " + message;
    return result;
}
Example 36
Project: jTalk-master  File: DateTimeEditor.java View source code
@Override
public void setAsText(String text) {
    if (text != null && !text.isEmpty()) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(this.format);
        try {
            setValue(dateTimeFormatter.parseDateTime(text));
        } catch (IllegalArgumentException e) {
            setValue(null);
        }
    }
}
Example 37
Project: levelup-java-examples-master  File: DatePlusYears.java View source code
@Test
public void add_years_to_date_in_java_joda() {
    DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0);
    DateTime fortyNinersSuck = superBowlXLV.plusYears(2);
    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
    logger.info(superBowlXLV.toString(fmt));
    logger.info(fortyNinersSuck.toString(fmt));
    assertTrue(fortyNinersSuck.isAfter(superBowlXLV));
}
Example 38
Project: logback-android-master  File: DateFormatPerf_Tapp.java View source code
static double doRawJoda() {
    //    DateTimeFormatter jodaFormat = DateTimeFormat.forPattern(ISO8601_PATTERN);
    long timeInMillis = new Date().getTime();
    long start = System.nanoTime();
    for (int i = 0; i < RUN_LENGTH; ++i) {
    //      jodaFormat.print(timeInMillis);
    }
    return (System.nanoTime() - start) * 1.0d / RUN_LENGTH;
}
Example 39
Project: logback-master  File: DateFormatPerf_Tapp.java View source code
static double doRawJoda() {
    // DateTimeFormatter jodaFormat = DateTimeFormat.forPattern(ISO8601_PATTERN);
    long timeInMillis = new Date().getTime();
    long start = System.nanoTime();
    for (int i = 0; i < RUN_LENGTH; ++i) {
    // jodaFormat.print(timeInMillis);
    }
    return (System.nanoTime() - start) * 1.0d / RUN_LENGTH;
}
Example 40
Project: mifos-head-master  File: DateFormatter.java View source code
/**
     * @param args
     *            a list of arguments passed in from FTL in this order:
     *            <ul>
     *            <li>date object to be formatted. It can be an instance of either java.util.Date,
     *            org.joda.time.DateTime or org.joda.time.LocalDate</li>
     *            <li>pattern: date format pattern see {@link java.text.SimpleDateFormat}</li>
     *            <li>locale: an instance of java.util.Locale</li>
     *            </ul>
     */
@Override
public Object exec(List args) throws TemplateModelException {
    if (args.size() != 3) {
        throw new IllegalArgumentException("Wrong arguments");
    }
    Object date = DeepUnwrap.unwrap((TemplateModel) args.get(0));
    String pattern = (String) DeepUnwrap.unwrap((TemplateModel) args.get(1));
    Locale locale = (Locale) DeepUnwrap.unwrap((TemplateModel) args.get(2));
    if (date instanceof LocalDate) {
        date = ((LocalDate) date).toDateTimeAtStartOfDay();
    }
    String formatted = "";
    if (date instanceof DateTime) {
        formatted = DateTimeFormat.forPattern(pattern).withLocale(locale).print((DateTime) date);
    } else if (date instanceof Date) {
        formatted = new SimpleDateFormat(pattern, locale).format((Date) date);
    } else if (date != null) {
        throw new IllegalArgumentException("Unsupported date type: " + date.getClass());
    }
    return formatted;
}
Example 41
Project: MozuAndroidInStoreAssistant-master  File: FulfillmentItemFulfilledRow.java View source code
@Override
public void bindData(IData data) {
    ButterKnife.inject(this);
    if (data instanceof FulfillmentFulfilledDataItem) {
        FulfillmentFulfilledDataItem fulfillmentPickupItem = (FulfillmentFulfilledDataItem) data;
        mFulfillmentName.setText(getContext().getResources().getString(R.string.fulfillment_pickup_number) + String.valueOf(fulfillmentPickupItem.getPickupCount()));
        int totalItemCount = 0;
        for (PickupItem item : fulfillmentPickupItem.getPickup().getItems()) {
            totalItemCount += item.getQuantity();
        }
        DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yy  hh:mm a");
        String pickUpDate = formatter.print(fulfillmentPickupItem.getPickup().getFulfillmentDate().getMillis());
        mFulfillmentDate.setText(pickUpDate);
        mItemCount.setText(String.valueOf(totalItemCount) + " " + getContext().getString(R.string.fulfillment_items_label));
        mLocation.setText(fulfillmentPickupItem.getPickup().getFulfillmentLocationCode());
    }
}
Example 42
Project: mt-flume-master  File: TestRegexExtractorInterceptorMillisSerializer.java View source code
@Test
public void shouldReturnMillisFromPattern() {
    RegexExtractorInterceptorMillisSerializer fixture = new RegexExtractorInterceptorMillisSerializer();
    Context context = new Context();
    String pattern = "yyyy-MM-dd HH:mm:ss";
    context.put("pattern", pattern);
    fixture.configure(context);
    DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
    long time = (System.currentTimeMillis() / 1000L) * 1000L;
    Assert.assertEquals(String.valueOf(time), fixture.serialize(formatter.print(time)));
}
Example 43
Project: netflix-commons-master  File: TimeUtil.java View source code
/**
	 * Converts the given time format string to a {@link org.joda.time.format.DateTimeFormatter} instance.
	 *
	 * @param formatName A name used to identify the given time format. This is mainly used for error reporting.
	 * @param timeFormat The date time format to be converted.
	 *
	 * @return A {@link org.joda.time.format.DateTimeFormatter} instance of the given time format.
	 *
	 * @throws IllegalArgumentException if the given time format is invalid.
	 */
public static DateTimeFormatter toDateTimeFormatter(String formatName, String timeFormat) {
    DateTimeFormatter formatter = null;
    try {
        formatter = DateTimeFormat.forPattern(timeFormat);
    } catch (IllegalArgumentException e) {
        IllegalArgumentException iae = new IllegalArgumentException(String.format("Invalid time format for the property %s: '%s'", formatName, timeFormat), e.getCause());
        iae.setStackTrace(e.getStackTrace());
        throw iae;
    }
    return formatter;
}
Example 44
Project: nico2ical-master  File: DeleteOldNicoliveIndexController.java View source code
/*
     * (non-Javadoc) {@inheritDoc}
     */
@Override
public Navigation run() throws Exception {
    LOGGER.info("BEGIN: " + this.getClass().getName());
    DateTime datetime = new DateTime();
    DateTime from = datetime.minusDays(MINUS_DAYS);
    nicoliveService.deleteOldIndex(from.toDate());
    if (LOGGER.isLoggable(Level.INFO)) {
        DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        LOGGER.info("NicoliveIndex(before " + from.toString(df) + ") was deleted.");
    }
    LOGGER.info("END: " + this.getClass().getName());
    return null;
}
Example 45
Project: objectlabkit-master  File: DefaultHolidayCalendarTest.java View source code
/**
     * See JODA issue:
     * http://joda-interest.219941.n2.nabble.com/LocalDate-equals-method-bug-td7572429.html
     */
public void testForDateWithDifferentChronologies() {
    final LocalDate localDate2 = new LocalDate(2012, 6, 21);
    final Set<LocalDate> s = new HashSet<LocalDate>();
    s.add(localDate2);
    final HolidayCalendar<LocalDate> holidayCalendar = new DefaultHolidayCalendar<LocalDate>(s, new LocalDate("2009-01-01"), new LocalDate("2009-12-01"));
    assertTrue("Date with Chronology " + localDate2.getChronology(), holidayCalendar.isHoliday(localDate2));
    final DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd HH:mm");
    final Calendar calendar = dateTimeFormat.parseDateTime("20120621 09:00").toCalendar(null);
    final LocalDate localDate1 = new LocalDate(calendar);
    assertTrue("Date with Chronology " + localDate1.getChronology(), holidayCalendar.isHoliday(localDate1));
}
Example 46
Project: OpenETSMobile2-master  File: NewsAdapter.java View source code
@SuppressLint("DefaultLocale")
@Override
public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder;
    if (view != null) {
        holder = (ViewHolder) view.getTag();
    } else {
        view = inflater.inflate(R.layout.row_news, parent, false);
        holder = new ViewHolder();
        holder.tvTitre = (TextView) view.findViewById(R.id.tv_row_news_titre);
        holder.tvDate = (TextView) view.findViewById(R.id.tv_row_news_date);
        holder.imageSource = (ImageView) view.findViewById(R.id.iv_news_source);
        view.setTag(holder);
    }
    Nouvelle item = getItem(position);
    holder.tvTitre.setText(item.getTitle());
    String updatedTime = item.getUpdated_time();
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime date = dateTimeFormatter.parseDateTime(updatedTime);
    DateTimeFormatter dateToDisplay = DateTimeFormat.forPattern("dd MMM yyyy");
    holder.tvDate.setText(dateToDisplay.print(date));
    holder.tvTitre.setText(item.getTitle());
    holder.imageSource.setImageResource(item.getImageResource());
    return view;
}
Example 47
Project: Quality-Tools-for-Android-master  File: HelloAndroidActivity.java View source code
@Override
public void onClick(View v) {
    if (computer != null) {
        textView.setText(String.valueOf(computer.getResult()));
    } else {
        // only tested by unit tests, not it tests
        textView.setText(R.string.text_no_computer);
    }
    DateTime dt = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM, yyyy");
    String dateString = fmt.print(dt);
    Toast.makeText(HelloAndroidActivity.this, dateString, Toast.LENGTH_LONG).show();
}
Example 48
Project: quickml-master  File: LibSVMFormatReader.java View source code
public List<ClassifierInstance> readLibSVMFormattedInstances(String path, String dateAttribute) {
    List<ClassifierInstance> instances = Lists.newArrayList();
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        for (String line; (line = br.readLine()) != null; ) {
            List<String> rawInstance = Arrays.asList(line.split(" "));
            Double label = Double.valueOf(rawInstance.get(0));
            AttributesMap map = AttributesMap.newHashMap();
            DateTime instanceTimeStamp = null;
            for (String rawAttributeAndValue : rawInstance.subList(1, rawInstance.size())) {
                String[] attributeAndValue = rawAttributeAndValue.split(":");
                String attribute = attributeAndValue[0];
                String value = attributeAndValue[1];
                if (attribute.equals(dateAttribute)) {
                    //format of T may be wrong
                    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                    instanceTimeStamp = new DateTime(dateTimeFormatter.parseMillis((String) value));
                } else {
                    try {
                        //add numeric variable as Double
                        map.put(attribute, Double.parseDouble(value));
                    } catch (NumberFormatException e) {
                        map.put(attribute, value);
                    }
                }
            }
            instances.add(new ClassifierInstance(map, label, instanceTimeStamp));
        }
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
    return instances;
}
Example 49
Project: Raigad-master  File: YearlyIndexNameFilter.java View source code
@Override
public boolean filter(String name) {
    if (name.length() < 5) {
        return false;
    }
    Pattern pattern = Pattern.compile(YEARLY_PATTERN);
    Matcher matcher = pattern.matcher(name);
    if (!matcher.matches())
        return false;
    String date = name.substring(name.length() - 4, name.length());
    try {
        DateTime.parse(date, DateTimeFormat.forPattern("YYYY"));
        return true;
    } catch (Exception e) {
        return false;
    }
}
Example 50
Project: saos-master  File: SourceCcJudgmentUrlFactory.java View source code
String createSourceJudgmentsUrl(int pageNo, int pageSize, DateTime publicationDateFrom) {
    String url = ccJudgmentListSourceUrl + "?offset=" + pageSize * pageNo + "&limit=" + pageSize + "&sort=signature|asc";
    if (publicationDateFrom != null) {
        publicationDateFrom = publicationDateFrom.toDateTime(DateTimeZone.forID(timeZoneId));
        url += "&publicationDateFrom=" + publicationDateFrom.toString(DateTimeFormat.forPattern(queryDateFromFormat));
    }
    return url;
}
Example 51
Project: spring-data-cloudant-master  File: DateTimeDataAdapter.java View source code
@Override
public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
    for (String format : DATE_FORMATS) {
        try {
            return DateTime.parse(json.getAsString(), DateTimeFormat.forPattern(format).withZoneUTC());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    throw new JsonParseException("Unparseable date: \"" + json.getAsString() + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
Example 52
Project: suro-master  File: TimeUtil.java View source code
/**
	 * Converts the given time format string to a {@link org.joda.time.format.DateTimeFormatter} instance.
	 *
	 * @param formatName A name used to identify the given time format. This is mainly used for error reporting.
	 * @param timeFormat The date time format to be converted.
	 *
	 * @return A {@link org.joda.time.format.DateTimeFormatter} instance of the given time format.
	 *
	 * @throws IllegalArgumentException if the given time format is invalid.
	 */
public static DateTimeFormatter toDateTimeFormatter(String formatName, String timeFormat) {
    DateTimeFormatter formatter = null;
    try {
        formatter = DateTimeFormat.forPattern(timeFormat);
    } catch (IllegalArgumentException e) {
        IllegalArgumentException iae = new IllegalArgumentException(String.format("Invalid time format for the property %s: '%s'", formatName, timeFormat), e.getCause());
        iae.setStackTrace(e.getStackTrace());
        throw iae;
    }
    return formatter;
}
Example 53
Project: twittererer-master  File: TimelineConverter.java View source code
private static String dateToAge(String createdAt, DateTime now) {
    if (createdAt == null) {
        return "";
    }
    DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_FORMAT);
    try {
        DateTime created = dtf.parseDateTime(createdAt);
        if (Seconds.secondsBetween(created, now).getSeconds() < 60) {
            return Seconds.secondsBetween(created, now).getSeconds() + "s";
        } else if (Minutes.minutesBetween(created, now).getMinutes() < 60) {
            return Minutes.minutesBetween(created, now).getMinutes() + "m";
        } else if (Hours.hoursBetween(created, now).getHours() < 24) {
            return Hours.hoursBetween(created, now).getHours() + "h";
        } else {
            return Days.daysBetween(created, now).getDays() + "d";
        }
    } catch (IllegalArgumentException e) {
        return "";
    }
}
Example 54
Project: UniApp-master  File: Util.java View source code
public static String getDateFormattedFromString(String m) {
    DateTimeFormatter format = DateTimeFormat.forPattern("dd/MMMM/yyyy").withLocale(Locale.ITALY);
    DateTime instance = format.parseDateTime(m.toLowerCase());
    int month = instance.getMonthOfYear() - 1;
    int day = instance.getDayOfMonth();
    int year = instance.getYear();
    Calendar c = Calendar.getInstance();
    c.set(year, month, day);
    SimpleDateFormat f = new SimpleDateFormat("dd/MM/yy");
    String data = f.format(c.getTime());
    return data;
}
Example 55
Project: spring-framework-master  File: JodaTimeFormattingTests.java View source code
@Test
public void testJodaTimePatternsForStyle() {
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("SS", LocaleContextHolder.getLocale()));
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("LL", LocaleContextHolder.getLocale()));
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("FF", LocaleContextHolder.getLocale()));
}
Example 56
Project: spring-js-master  File: JodaTimeFormattingTests.java View source code
@Test
public void testJodaTimePatternsForStyle() {
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("SS", LocaleContextHolder.getLocale()));
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("LL", LocaleContextHolder.getLocale()));
    System.out.println(org.joda.time.format.DateTimeFormat.patternForStyle("FF", LocaleContextHolder.getLocale()));
}
Example 57
Project: spring-xd-master  File: ExampleProcessingChainTests.java View source code
/**
	 * Test a processing chain that provides a source. Verify the result.
	 */
@Test
public void chainWithSource() {
    String processingChainUnderTest = "time | transform --expression='T(org.joda.time.format.DateTimeFormat).forPattern(\"yyyy-MM-dd HH:mm:ss\").parseDateTime(payload)'";
    SingleNodeProcessingChainConsumer chain = chainConsumer(application, "dateToDateTime", processingChainUnderTest);
    Object payload = chain.receivePayload(RECEIVE_TIMEOUT);
    assertTrue(payload instanceof DateTime);
    chain.destroy();
}
Example 58
Project: AGIA-master  File: ChronoFileSystemResourceFactory.java View source code
public Resource getResource() throws ResourceCreationException {
    FileSystemResource aFileSystemResource = null;
    try {
        DateTimeFormatter aFormatter = DateTimeFormat.forPattern(dateFormat);
        StringBuilder aFilename = new StringBuilder();
        aFilename.append(prefix).append(aFormatter.print(new Instant())).append(suffix);
        aFileSystemResource = new FileSystemResource(aFilename.toString());
    } catch (Exception e) {
        throw new ResourceCreationException(e);
    }
    return aFileSystemResource;
}
Example 59
Project: android-anpr-master  File: HttpRequest.java View source code
protected void onPostExecute(vehRecord vehicle) {
    vehView.VRM.setText(vehicle.getVRM());
    vehView.Make.setText(vehicle.getMake());
    vehView.Model.setText(vehicle.getModel());
    vehView.Tax.setText(DateTimeFormat.forPattern("dd MM YY").print(vehicle.getTax()));
    vehView.MOT.setText(vehicle.isMOTed());
    vehView.Insured.setText(vehicle.getInsured());
    vehView.LoadingFrame.setVisibility(View.GONE);
}
Example 60
Project: biller-simulator-master  File: PaymentPostpaidTest.java View source code
@Test
public void testPaymentNormal() throws Exception {
    String idpel = "123456789011";
    String switcher = "ARTIVIS";
    String bank = "BANKABC";
    ISOMsg inqRequest = new ISOMsg();
    inqRequest.setMTI(MTIConstants.INQUIRY_REQUEST);
    inqRequest.set(2, "51501");
    inqRequest.set(11, "123456789012");
    inqRequest.set(12, DateTimeFormat.forPattern("yyyyMMddHHmmss").print(new Date().getTime()));
    inqRequest.set(26, "6012");
    inqRequest.set(32, bank);
    inqRequest.set(48, switcher + idpel);
    PlnChannel channel = createChannel();
    channel.connect();
    channel.send(inqRequest);
    ISOMsg inqResponse = channel.receive();
    channel.disconnect();
    assertEquals(ResponseCode.SUCCESSFUL, inqResponse.getString(39));
    ISOMsg payRequest = (ISOMsg) inqResponse.clone();
    payRequest.setMTI(MTIConstants.PAYMENT_REQUEST);
    payRequest.unset(39);
    String bit48Inquiry = inqResponse.getString(48);
    String billstatus = bit48Inquiry.substring(19, 20);
    payRequest.set(48, bit48Inquiry.substring(0, 20) + billstatus + bit48Inquiry.substring(20));
    channel.connect();
    channel.send(payRequest);
    ISOMsg payResponse = channel.receive();
    channel.disconnect();
    assertEquals(ResponseCode.SUCCESSFUL, payResponse.getString(39));
}
Example 61
Project: CAN-2015-master  File: FeedListAdapter.java View source code
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    final Feed object = mMainListItem.get(position);
    if (object != null) {
        JodaTimeAndroid.init(MainApplication.getContext());
        holder.tvTitle.setText(object.title);
        Date date = object.pubDate;
        DateTime dt = new DateTime(date);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("E e MMMM yyyy HH:mm:ss");
        String str = fmt.print(dt);
        holder.tvDate.setText(str);
        if (object.photoUrl != null) {
            String imageUrl = object.photoUrl;
            aQ.id(holder.ivThumbnail).progress(holder.progress).image(imageUrl, true, true, 0, 0, null, 0, 1.0f);
        }
    }
    Typeface Roboto_Regular = Typeface.createFromAsset(mContext.getAssets(), "Roboto-Regular.ttf");
    holder.tvTitle.setTypeface(Roboto_Regular);
}
Example 62
Project: commcare-master  File: ArchivedFormPurgeTest.java View source code
/**
     * Ensure that the correct number of forms are purged given different
     * validity ranges
     */
@Test
public void testSavedFormPurge() {
    int SAVED_FORM_COUNT = 5;
    String firstFormCompletionDate = "Mon Oct 05 16:17:01 -0400 2015";
    DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy");
    DateTime startTestDate = dtf.parseDateTime(firstFormCompletionDate);
    DateTime twoMonthsLater = startTestDate.plusMonths(2);
    assertEquals("Only 1 form should remain if we're 2 months past the 1st form's create date.", SAVED_FORM_COUNT - 1, PurgeStaleArchivedFormsTask.getSavedFormsToPurge(twoMonthsLater).size());
    DateTime twentyYearsLater = startTestDate.plusYears(20);
    assertEquals("All forms should be purged if we are way in the future.", SAVED_FORM_COUNT, PurgeStaleArchivedFormsTask.getSavedFormsToPurge(twentyYearsLater).size());
    assertEquals("When the time is the 1st form's creation time, no forms should be purged", 0, PurgeStaleArchivedFormsTask.getSavedFormsToPurge(startTestDate).size());
}
Example 63
Project: csv2rdf4lod-automation-master  File: TempTest.java View source code
public static void main(String[] args) {
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");
    //Setting 2011 Fall DST day.
    DateTime st = new DateTime(2011, 11, 6, 0, 0, CHICAGO);
    DateTime et = new DateTime(2011, 11, 6, 0, 0, CHICAGO);
    //======================================
    for (int i = 0; i <= 24; i++) {
        try {
            if (i > 0) {
                st = st.minuteOfDay().addToCopy(60);
            }
            et = et.minuteOfDay().addToCopy(60);
            System.out.println("START TIME = { " + fmt.print(st) + " } END TIME =  {" + fmt.print(et) + " }");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//=====================================
//        A a = new A();
//        System.out.println(a.getValue(0));
//        
//        ReadablePartial a1 = a;
//        System.out.println(a1.compareTo(null));
//        DateTime dt = new DateTime(SAO_PAOLO)
//        .withYear(2011)
//        .withMonthOfYear(10)
//        .withDayOfMonth(15)
//        .withHourOfDay(23)
//        .withMinuteOfHour(59)
//        .withSecondOfMinute(59)
//        .withMillisOfSecond(999);
//        System.out.println(dt);
//        dt = dt.plusMillis(1);
//        System.out.println(dt);
//        
////        DateTime dt2 = new DateTime(SAO_PAOLO)
////        .withYear(2011)
////        .withMonthOfYear(10)
////        .withDayOfMonth(16)
////        .withHourOfDay(0)
////        .withMinuteOfHour(0)
////        .withSecondOfMinute(0)
////        .withMillisOfSecond(0);
//        
//        DateTime dt3 = new DateTime(SAO_PAOLO)
//        .withYear(2011)
//        .withMonthOfYear(10)
//        .withDayOfMonth(16)
//        .withTimeAtStartOfDay();
////        .millisOfDay()
////        .withMinimumValue();
//        System.out.println(dt3);
//        
//        DateTime dt4 = new DateTime(SAO_PAOLO)
//        .withYear(2011)
//        .withMonthOfYear(10)
//        .withDayOfMonth(16)
//        .toDateMidnight().toDateTime();
//        System.out.println(dt4);
}
Example 64
Project: developer-bookshelf-heroku-master  File: BookService.java View source code
/**
	 * Restore the original set of books to the database.
	 */
public void restoreDefaultBooks() {
    ClassPathResource resource = new ClassPathResource("/config/liquibase/books.csv");
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        // Skip first line that only holds headers.
        br.readLine();
        String line;
        while ((line = br.readLine()) != null) {
            String[] words = line.split("~");
            Integer version = Integer.valueOf(words[0]);
            String name = words[1];
            String publisher = words[2];
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
            DateTime dateOfPublication = formatter.parseDateTime(words[3]);
            String description = words[4];
            String photo = words[5];
            Book b = new Book(version, name, publisher, dateOfPublication, description, photo);
            bookRepository.save(b);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // Release resources.
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Example 65
Project: Doctors-master  File: ParametrosAgendamento.java View source code
public static ParametrosAgendamento getParametrosDefault() {
    ParametrosAgendamento padrao = new ParametrosAgendamento();
    padrao.setHoraInicioAtendimento(new LocalTime(8, 0));
    padrao.setHoraFimAtendimento(new LocalTime(17, 30));
    padrao.setDataInicial(new LocalDate().plusDays(1));
    padrao.setDataFinal(new LocalDate(padrao.getDataInicial()).plusMonths(2));
    padrao.setMinutosPorConsulta(Minutes.minutes(30));
    padrao.setDataFormatter(DateTimeFormat.forPattern("dd/MM/yyyy"));
    padrao.setHoraFormatter(DateTimeFormat.forPattern("HH:mm"));
    padrao.setHoraInicioAlmoco(new LocalTime(11, 59));
    padrao.setHoraFimAlmoco(new LocalTime(14, 00));
    return padrao;
}
Example 66
Project: elmis-master  File: VaccineInventoryReportService.java View source code
public List<Map<String, String>> getDistributionCompletenessReport(String periodStart, String periodEnd, Long districtId, Pagination pagination) {
    Date startDate, endDate;
    startDate = DateTimeFormat.forPattern(DATE_FORMAT).parseDateTime(periodStart).toDate();
    endDate = DateTimeFormat.forPattern(DATE_FORMAT).parseDateTime(periodEnd).toDate();
    return repository.getDistributionCompletenessReport(startDate, endDate, districtId, pagination);
}
Example 67
Project: EMB-master  File: TimestampFormat.java View source code
public static DateTimeZone parseDateTimeZone(String s) {
    if (s.startsWith("+") || s.startsWith("-")) {
        return DateTimeZone.forID(s);
    } else if (s.equals("Z")) {
        return DateTimeZone.UTC;
    } else {
        try {
            int rawOffset = (int) DateTimeFormat.forPattern("z").parseMillis(s);
            if (rawOffset == 0) {
                return DateTimeZone.UTC;
            }
            int offset = rawOffset / -1000;
            int h = offset / 3600;
            int m = offset % 3600;
            return DateTimeZone.forOffsetHoursMinutes(h, m);
        } catch (IllegalArgumentException ex) {
        }
        // we want to only return timezone if exact match, otherwise exception
        if (availableTimeZoneNames.contains(s)) {
            //return TimeZone.getTimeZone(s);
            return DateTimeZone.forID(s);
        }
        return null;
    }
}
Example 68
Project: embulk-master  File: TimestampFormat.java View source code
public static DateTimeZone parseDateTimeZone(String s) {
    if (s.startsWith("+") || s.startsWith("-")) {
        return DateTimeZone.forID(s);
    } else if (s.equals("Z")) {
        return DateTimeZone.UTC;
    } else {
        try {
            int rawOffset = (int) DateTimeFormat.forPattern("z").parseMillis(s);
            if (rawOffset == 0) {
                return DateTimeZone.UTC;
            }
            int offset = rawOffset / -1000;
            int h = offset / 3600;
            int m = offset % 3600;
            return DateTimeZone.forOffsetHoursMinutes(h, m);
        } catch (IllegalArgumentException ex) {
        }
        // we want to only return timezone if exact match, otherwise exception
        if (availableTimeZoneNames.contains(s)) {
            //return TimeZone.getTimeZone(s);
            return DateTimeZone.forID(s);
        }
        return null;
    }
}
Example 69
Project: financial-projects-master  File: UnitOverheadHeaderComponent.java View source code
@Override
public void write(HSSFSheet sheet, HSSFFont headersFont) {
    CellStyle style = sheet.getWorkbook().createCellStyle();
    style.setFont(headersFont);
    int rowNum = sheet.getLastRowNum() + 2;
    HSSFRow row = sheet.createRow(rowNum++);
    HSSFCell cell = row.createCell(0);
    cell.setCellValue(BundleUtil.getFormattedStringFromResourceBundle("resources/projectsResources", "financialprojectsreports.unitOverheadHeader.label.unit"));
    cell.setCellStyle(style);
    cell = row.createCell(1);
    cell.setCellValue(unit.getName());
    row = sheet.createRow(rowNum++);
    cell = row.createCell(0);
    cell.setCellValue(BundleUtil.getFormattedStringFromResourceBundle("resources/projectsResources", "financialprojectsreports.unitOverheadHeader.label.costCenter"));
    cell.setCellStyle(style);
    cell = row.createCell(1);
    cell.setCellValue(unit.getCostCenterUnit().getCostCenter());
    row = sheet.createRow(rowNum++);
    cell = row.createCell(0);
    cell.setCellValue(BundleUtil.getFormattedStringFromResourceBundle("resources/projectsResources", "financialprojectsreports.unitOverheadHeader.label.date"));
    cell.setCellStyle(style);
    cell = row.createCell(1);
    DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYY-MM-dd");
    cell.setCellValue(fmt.print(new DateTime()));
}
Example 70
Project: graylog2-server-master  File: DateConverter.java View source code
@Override
@Nullable
public Object convert(@Nullable String value) {
    if (isNullOrEmpty(value)) {
        return null;
    }
    LOG.debug("Trying to parse date <{}> with pattern <{}> and timezone <{}>.", value, dateFormat, timeZone);
    final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withDefaultYear(YearMonth.now(timeZone).getYear()).withZone(timeZone);
    return DateTime.parse(value, formatter);
}
Example 71
Project: incubator-tajo-master  File: ToCharTimestamp.java View source code
@Override
public Datum eval(Tuple params) {
    if (params.isNull(0) || params.isNull(1)) {
        return NullDatum.get();
    }
    TimestampDatum valueDatum = (TimestampDatum) params.get(0);
    Datum pattern = params.get(1);
    if (formatter == null || !constantFormat) {
        formatter = DateTimeFormat.forPattern(pattern.asChars());
    }
    return DatumFactory.createText(valueDatum.toChars(formatter));
}
Example 72
Project: jangod-master  File: DatetimeFilter.java View source code
@Override
public Object filter(Object object, JangodInterpreter interpreter, String... arg) throws InterpretException {
    if (object == null) {
        return object;
    }
    if (// joda DateTime
    object instanceof DateTime) {
        DateTimeFormatter formatter;
        DateTimeFormatter a = DateTimeFormat.forPattern(interpreter.evaluateExpressionAsString(arg[0]));
        if (arg.length == 1) {
            DateTimeFormatter forPattern = a;
            JodaTimeContext jodaTimeContext = JodaTimeContextHolder.getJodaTimeContext();
            if (jodaTimeContext == null) {
                jodaTimeContext = new JodaTimeContext();
            }
            formatter = jodaTimeContext.getFormatter(forPattern);
        } else if (arg.length == 2) {
            formatter = a.withChronology(ISOChronology.getInstance(DateTimeZone.forID(interpreter.evaluateExpressionAsString(arg[1]))));
        } else {
            throw new InterpretException("filter date expects 1 or 2 args >>> " + arg.length);
        }
        return formatter.print((DateTime) object);
    } else {
        SimpleDateFormat sdf;
        if (arg.length == 1) {
            sdf = new SimpleDateFormat(interpreter.evaluateExpressionAsString(arg[0]));
            sdf.setTimeZone(interpreter.getConfiguration().getTimezone());
        } else if (arg.length == 2) {
            sdf = new SimpleDateFormat(interpreter.evaluateExpressionAsString(arg[0]));
            sdf.setTimeZone(TimeZone.getTimeZone(interpreter.evaluateExpressionAsString(arg[1])));
        } else {
            throw new InterpretException("filter date expects 1 or 2 args >>> " + arg.length);
        }
        return sdf.format(object);
    }
}
Example 73
Project: jtrade-master  File: CsvBarFileReader.java View source code
private void readHeader() throws IOException {
    tz = DateTimeZone.getDefault();
    dateFormatter = DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss");
    String line = null;
    while ((line = readLine()) != null) {
        if (line.startsWith("# symbol")) {
            symbol = SymbolFactory.getSymbol(line.substring(9).trim());
            continue;
        }
        if (line.startsWith("# barSizeSeconds")) {
            barSize = Duration.standardSeconds(Integer.parseInt(line.substring(17).trim()));
            continue;
        }
        if (line.startsWith("# timeZone")) {
            tz = DateTimeZone.forID(line.substring(11).trim());
            dateFormatter = dateFormatter.withZone(tz);
            continue;
        }
        if (line.startsWith("# dateFormat")) {
            dateFormatter = DateTimeFormat.forPattern(line.substring(13).trim()).withZone(tz);
            continue;
        }
        if (line.startsWith("#")) {
            continue;
        }
        if (line.startsWith("date,")) {
            return;
        }
    }
}
Example 74
Project: maven-numbers-plugin-master  File: TestDateBasic.java View source code
@Test
public void testNumber1() throws Exception {
    final DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd_HHmmss");
    final File jarLocation = TestUtils.runPackageGoal("date", "number1");
    final JarFile jarFile = new JarFile(jarLocation);
    final Manifest manifest = jarFile.getManifest();
    final Attributes attributes = manifest.getMainAttributes();
    final String regular = attributes.getValue("regular");
    Assert.assertNotNull(regular);
    final DateTime regularDate = format.parseDateTime(regular);
    Assert.assertNotNull(regularDate);
    final String regularUtc = attributes.getValue("regular-utc");
    Assert.assertNotNull(regularUtc);
    final DateTime regularUtcDate = format.parseDateTime(regularUtc);
    Assert.assertNotNull(regularUtcDate);
    final String epoch = attributes.getValue("epoch");
    Assert.assertNotNull(epoch);
    final DateTime epochDate = format.parseDateTime(epoch);
    Assert.assertNotNull(epochDate);
    final String epochUtc = attributes.getValue("epoch-utc");
    Assert.assertNotNull(epochUtc);
    final DateTime epochUtcDate = format.parseDateTime(epochUtc);
    Assert.assertNotNull(epochUtcDate);
}
Example 75
Project: ModularityCheck-master  File: VersionControlManager.java View source code
/**
	 * Transforma duas datas textuais (ex: "2008-06-14") em um objeto Interval,
	 * que representa um intervalo de tempo.
	 */
private Interval getIntervalFromParams(String start_date_str, String end_date_str) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("y-M-d");
    // DateMidnight e um DateTime onde a hora e sempre 00:00.
    DateMidnight start_date = new DateMidnight(formatter.parseDateTime(start_date_str));
    DateMidnight end_date = new DateMidnight(formatter.parseDateTime(end_date_str));
    return new Interval(start_date, end_date);
}
Example 76
Project: mozu-java-master  File: Crypto.java View source code
public static final boolean isRequestValid(ApiContext apiContext, String body) {
    boolean isValid = false;
    if (Crypto.getHash(AppAuthenticator.getInstance().getAppAuthInfo().getSharedSecret(), apiContext.getHeaderDate(), body).equals(apiContext.getHMACSha256())) {
        isValid = true;
    } else {
        StringBuilder msg = new StringBuilder("Request is not authorized.");
        logger.warn(msg.toString());
    }
    // Check if date has expired
    int requestValidTimeSeconds = MozuConfig.getDefaultEventRequestTimeout();
    String dateString = apiContext.getHeaderDate();
    DateTimeFormatter dtf = DateTimeFormat.forPattern("E, dd MMM yyyy HH:mm:ss zzz");
    DateTime dTime = dtf.parseDateTime(dateString);
    long deltaTime = (DateTime.now().getMillis() - dTime.getMillis()) / 1000;
    if (deltaTime > requestValidTimeSeconds) {
        isValid = false;
    }
    return isValid;
}
Example 77
Project: netxilia-master  File: TestDateUtils.java View source code
@Test
public void testPartialClass() {
    Assert.assertEquals(LocalTime.class, DateUtils.getPartialClass(DateTimeFormat.forPattern("mm:HH:ss")));
    Assert.assertEquals(LocalDate.class, DateUtils.getPartialClass(DateTimeFormat.forPattern("dd/MM/yyyy")));
    Assert.assertEquals(LocalDateTime.class, DateUtils.getPartialClass(DateTimeFormat.forPattern("dd/MM/yyyy mm:HH:ss")));
}
Example 78
Project: n_e_b_u_l_a-master  File: JsonProviderTest.java View source code
public void testPerson() throws Exception {
    //@formatter:off
    String text = "" + "type Person { " + "	!Name;" + "	Age;" + "	Decimal;" + "	Date;" + "	Time;" + "	Datetime;" + "	Timestamp;" + "};";
    //@formatter:on		
    final Type type;
    type = typeload.testDefineNebula(new StringReader(text)).get(0);
    // store = persistence.define(String.class,Entity.class,
    // type.getName());
    DataHelper<Entity, Reader, Writer> json = JsonHelperProvider.getHelper(typeBrokers.getBroker(type.getName()));
    Entity n = new EditableEntity();
    n = json.readFrom(n, new StringReader("{" + "	\"Name\"		:\"wangshilian\",	" + "	\"Age\"			:12,					" + "	\"Decimal\"		:9876.5432,	" + "	\"Date\"		:\"2012-12-20\",	" + "	\"Time\"		:\"12:00:12\",	" + "	\"Datetime\"	:\"2012-12-20 23:58:59\",	" + "	\"Timestamp\"	:\"2012-12-20 23:58:59.789\"	" + "}"));
    assertEquals("wangshilian", n.get("Name"));
    assertEquals(12L, n.get("Age"));
    assertEquals(new BigDecimal("9876.5432"), n.get("Decimal"));
    DateTimeFormatter sdf;
    sdf = DateTimeFormat.forPattern("yyyy-MM-dd");
    assertEquals(sdf.parseDateTime("2012-12-20"), n.get("Date"));
    sdf = DateTimeFormat.forPattern("kk:mm:ss");
    assertEquals(sdf.parseDateTime("12:00:12"), n.get("Time"));
    sdf = DateTimeFormat.forPattern("yyyy-MM-dd kk:mm:ss");
    assertEquals(sdf.parseDateTime("2012-12-20 23:58:59"), n.get("Datetime"));
    sdf = DateTimeFormat.forPattern("yyyy-MM-dd kk:mm:ss.SSS");
    assertEquals(sdf.parseDateTime("2012-12-20 23:58:59.789").getMillis(), n.get("Timestamp"));
    Writer out = new StringWriter();
    json.stringifyTo(n, out);
    assertEquals("{\"Name\":\"wangshilian\"," + "\"Age\":12,\"Decimal\":9876.5432," + "\"Date\":\"2012-12-20\"," + "\"Time\":\"12:00:12\"," + "\"Datetime\":\"2012-12-20 23:58:59\"," + "\"Timestamp\":\"2012-12-20 23:58:59.789\"}", out.toString());
}
Example 79
Project: opacclient-master  File: CopiesAdapter.java View source code
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Copy copy = copies.get(position);
    setTextOrHide(copy.getBranch(), holder.tvBranch);
    setTextOrHide(copy.getDepartment(), holder.tvDepartment);
    setTextOrHide(copy.getLocation(), holder.tvLocation);
    setTextOrHide(copy.getShelfmark(), holder.tvShelfmark);
    setTextOrHide(copy.getStatus(), holder.tvStatus);
    setTextOrHide(copy.getReservations(), holder.tvReservations);
    setTextOrHide(copy.getUrl(), holder.tvUrl);
    if (copy.getReturnDate() != null) {
        holder.tvReturndate.setText(DateTimeFormat.shortDate().print(copy.getReturnDate()));
        holder.tvReturndate.setVisibility(View.VISIBLE);
    } else {
        holder.tvReturndate.setVisibility(View.GONE);
    }
}
Example 80
Project: penn-mobile-android-master  File: Venue.java View source code
/**
     * Get a mapping of meal names to open hours for all meals in the dining hall this week
     *
     * @return HashMap of meal name (lunch, dinner) to open hours expressed as a Joda Interval
     */
public HashMap<String, Interval> getHours() {
    DateTime currentTime = new DateTime();
    // Split by T gets the Y-M-D format to compare against the date in JSON
    DateTime tomorrow = currentTime.plusDays(1);
    DateTimeFormatter intervalFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    DateTime intervalDateTime;
    HashMap<String, Interval> intervals = new HashMap<>();
    for (VenueInterval interval : hours) {
        intervalDateTime = intervalFormatter.parseDateTime(interval.date);
        if (intervalDateTime.toLocalDate().equals(tomorrow.toLocalDate())) {
            intervals.putAll(interval.getIntervals());
        }
    }
    for (VenueInterval interval : hours) {
        intervalDateTime = intervalFormatter.parseDateTime(interval.date);
        if (intervalDateTime.toLocalDate().equals(currentTime.toLocalDate())) {
            for (Map.Entry<String, Interval> entry : interval.getIntervals().entrySet()) {
                if (entry.getValue().contains(currentTime) || currentTime.isBefore(entry.getValue().getStart())) {
                    intervals.put(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    return intervals;
}
Example 81
Project: poseidon-rest-master  File: InvoiceGeneratorControllerV1.java View source code
private String writeCSVFileToDisk(InvoiceData data, String csv) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd_HH:mm_ZZZ");
    data.filename = (data.filename != null ? data.filename + "-" : "").replace(" ", "_");
    DateTime now = PoseidonService.getNow();
    String filename = data.filename + formatter.print(now) + ".csv";
    String csvdir = PoseidonPropertyService.getProperty(CSV_DIR);
    csvdir = csvdir.endsWith("/") ? csvdir : csvdir + "/";
    new CsvWriter().writeCsvToFile(csv, filename, csvdir);
    return filename;
}
Example 82
Project: presto-kinesis-master  File: CustomDateTimeJsonKinesisFieldDecoder.java View source code
@Override
public long getLong() {
    if (isNull()) {
        return 0L;
    }
    if (value.canConvertToLong()) {
        return value.asLong();
    }
    checkNotNull(columnHandle.getFormatHint(), "formatHint is null");
    String textValue = value.isValueNode() ? value.asText() : value.toString();
    DateTimeFormatter formatter = DateTimeFormat.forPattern(columnHandle.getFormatHint()).withLocale(Locale.ENGLISH).withZoneUTC();
    return formatter.parseMillis(textValue);
}
Example 83
Project: presto-master  File: CustomDateTimeJsonFieldDecoder.java View source code
@Override
protected long getMillis() {
    if (isNull()) {
        return 0L;
    }
    if (value.canConvertToLong()) {
        return value.asLong();
    }
    requireNonNull(columnHandle.getFormatHint(), "formatHint is null");
    String textValue = value.isValueNode() ? value.asText() : value.toString();
    DateTimeFormatter formatter = DateTimeFormat.forPattern(columnHandle.getFormatHint()).withLocale(Locale.ENGLISH).withZoneUTC();
    return formatter.parseMillis(textValue);
}
Example 84
Project: qcadoo-master  File: DateTimeType.java View source code
@Override
public ValueAndError toObject(final FieldDefinition fieldDefinition, final Object value) {
    if (value instanceof Date) {
        return ValueAndError.withoutError(value);
    }
    try {
        DateTimeFormatter fmt = DateTimeFormat.forPattern(DateUtils.L_DATE_TIME_FORMAT);
        DateTime dt = fmt.parseDateTime(String.valueOf(value));
        int year = dt.getYear();
        if (year < 1500 || year > 2500) {
            return ValueAndError.withError("qcadooView.validate.field.error.invalidDateTimeFormat");
        }
        return ValueAndError.withoutError(dt.toDate());
    } catch (IllegalArgumentException e) {
        return ValueAndError.withError("qcadooView.validate.field.error.invalidDateTimeFormat");
    }
}
Example 85
Project: RedMenu-master  File: MealMenuUtil.java View source code
/** Prints each <code>MealMenu</code> in this Scraper to <code>System.out</code> in a clean format. 
     * 
     */
public static void printAll(ArrayList<MealMenu> menus) {
    for (MealMenu menu : menus) {
        System.out.println("Commons: " + menu.getCommonsName());
        System.out.println("Start Time: " + DateTimeFormat.mediumDateTime().print(menu.getMealInterval().getStart()));
        System.out.println("End Time: " + DateTimeFormat.mediumDateTime().print(menu.getMealInterval().getEnd()));
        System.out.println("Mod Time: " + DateTimeFormat.mediumDateTime().print(menu.getModDate()));
        System.out.println("Meal Name: " + menu.getMealName());
        System.out.println("Venues: ");
        for (Venue ven : menu.getVenues()) {
            System.out.println("    Venue Name: " + ven.getName());
            System.out.println("    Food Items:");
            for (FoodItem food : ven.getFoodItems()) {
                System.out.println("        " + food.getName() + " " + food.isVegan() + " " + food.isVegetarian());
            }
        }
    }
}
Example 86
Project: tajo-cdh-master  File: ToCharTimestamp.java View source code
@Override
public Datum eval(Tuple params) {
    if (params.isNull(0) || params.isNull(1)) {
        return NullDatum.get();
    }
    TimestampDatum valueDatum = (TimestampDatum) params.get(0);
    Datum pattern = params.get(1);
    if (formatter == null || !constantFormat) {
        formatter = DateTimeFormat.forPattern(pattern.asChars());
    }
    return DatumFactory.createText(valueDatum.toChars(formatter));
}
Example 87
Project: TinCanJava-master  File: HTTPResponse.java View source code
public DateTime getLastModified() {
    DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC();
    try {
        return DateTime.parse(this.getHeader("Last-Modified"), RFC1123_DATE_TIME_FORMATTER);
    } catch (Exception parseException) {
        return null;
    }
}
Example 88
Project: wonder-master  File: ERXJodaLocalTimeFormatter.java View source code
protected DateTimeFormatter formatter() {
    if (formatter == null) {
        formatter = DateTimeFormat.forPattern(_pattern);
        if (_chronology != null) {
            formatter = formatter.withChronology(_chronology);
        }
        if (_locale != null) {
            formatter = formatter.withLocale(_locale);
        }
        if (_zone != null) {
            formatter = formatter.withZone(_zone);
        }
    }
    return formatter;
}
Example 89
Project: bonaparte-java-master  File: CSVConfiguration.java View source code
// certain utility methods used by CSV parser / composers
public DateTimeFormatter determineDayFormatter() {
    try {
        return customDayFormat == null ? DateTimeFormat.forStyle(dateStyle.getToken() + "-") : DateTimeFormat.forPattern(customDayFormat);
    } catch (IllegalArgumentException e) {
        LOGGER.error("Provided format is not valid: " + customDayFormat, e);
        return DateTimeFormat.forPattern(DEFAULT_DAY_FORMAT);
    }
}
Example 90
Project: ABRAID-MP-master  File: JsonParserTest.java View source code
@Test
public void parseUsingSpecifiedDateFormat() {
    // Arrange
    String json = "{ \"name\": \"Boris Becker\", \"age\": 46, \"dateOfBirth\": \"1967-11-22 11:22:33+0400\" }";
    final String dateTimeFormatString = "yyyy-MM-dd HH:mm:ssZ";
    JsonParser parser = new JsonParser(DateTimeFormat.forPattern(dateTimeFormatString));
    // Act
    JsonParserTestPerson person = parser.parse(json, JsonParserTestPerson.class);
    // Assert
    assertThat(person.getName()).isEqualTo("Boris Becker");
    assertThat(person.getAge()).isEqualTo(46);
    DateTime expected = new DateTime("1967-11-22T11:22:33+0400");
    assertThat(person.getDateOfBirth().getMillis()).isEqualTo(expected.getMillis());
}
Example 91
Project: BlackboardVCPortlet-master  File: ViewAdminServerConfigController.java View source code
@ResourceMapping("datafixRecording")
public String datafixRecording(PortletRequest request, ResourceResponse response, ModelMap model) {
    String startDate = (String) request.getParameter("startDate");
    String endDate = (String) request.getParameter("endDate");
    DateTime sd = DateTime.parse(startDate, DateTimeFormat.forPattern("MM-dd-YYYY"));
    DateTime ed = DateTime.parse(endDate, DateTimeFormat.forPattern("MM-dd-YYYY"));
    if (sd != null && ed != null) {
        int errd = recordingService.datafixRecordings(sd, ed);
        if (errd > 0)
            logger.warn("During datafixRecording, " + errd + " failed to insert");
    } else {
        response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "400");
        response.setProperty("X-Status-Reason", "Validation failed");
    }
    return "json";
}
Example 92
Project: bookery-master  File: BookExporterOld.java View source code
private static void exportBatchWise(SolrServer server, File exportFolder, int batchSize, int offset, Gson gson) throws SolrServerException, IOException {
    QueryResponse response = SolrHandler.searchSolrIndex(server, "*:*", batchSize, offset);
    List<BookEntry> bookEntries = response.getBeans(BookEntry.class);
    System.out.println("Retrieved " + (bookEntries.size() + offset) + " of " + response.getResults().getNumFound());
    for (BookEntry bookEntry : bookEntries) {
        String bookTitle = bookEntry.getTitle();
        bookTitle = bookTitle.replaceAll(":", " ");
        File bookFolder = new File(exportFolder, bookEntry.getAuthor() + "-" + bookTitle);
        bookFolder.mkdirs();
        if (bookEntry.getFile() != null && bookEntry.getCover() != null) {
            File bookData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".mobi");
            Files.write(bookData.toPath(), bookEntry.getFile(), StandardOpenOption.CREATE_NEW);
            File coverData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".jpg");
            Files.write(coverData.toPath(), bookEntry.getCover(), StandardOpenOption.CREATE_NEW);
            Date dreleaseDate = null;
            if (bookEntry.getReleaseDate() != null) {
                DateTime dtReleaseDate = DateTime.parse(bookEntry.getReleaseDate(), DateTimeFormat.forPattern("YYYY-MM-dd"));
                dtReleaseDate = new DateTime(dtReleaseDate, DateTimeZone.UTC);
                dreleaseDate = dtReleaseDate.toDate();
            }
            DateTime dtUploadDate = new DateTime(DateTimeZone.UTC);
            File metaDataFile = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".json");
            String[] viewed = {};
            BookMetaData metaData = new BookMetaData(bookEntry.getAuthor(), bookEntry.getTitle(), bookEntry.getIsbn(), bookEntry.getPublisher(), bookEntry.getDescription(), bookEntry.getLanguage(), dreleaseDate, bookEntry.getMimeType(), dtUploadDate.toDate(), viewed, bookEntry.getShared());
            gson.toJson(metaData);
            Files.write(metaDataFile.toPath(), gson.toJson(metaData).getBytes(), StandardOpenOption.CREATE_NEW);
        }
    }
    if (response.getResults().getNumFound() > offset) {
        exportBatchWise(server, exportFolder, batchSize, offset + batchSize, gson);
    }
}
Example 93
Project: BudgetForce2-master  File: IllegalInstantException.java View source code
private static String createMessage(long instantLocal, String zoneId) {
    String localDateTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").print(new Instant(instantLocal));
    String zone = (zoneId != null ? " (" + zoneId + ")" : "");
    return "Illegal instant due to time zone offset transition (daylight savings time 'gap'): " + localDateTime + zone;
}
Example 94
Project: calendula-master  File: NotificationEventReceiver.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    long routineId;
    long scheduleId;
    String scheduleTime;
    LocalDate date;
    int action = intent.getIntExtra(CalendulaApp.INTENT_EXTRA_ACTION, -1);
    Log.d(TAG, "Notification event received - Action : " + action);
    String dateStr = intent.getStringExtra("date");
    if (dateStr != null) {
        date = DateTimeFormat.forPattern(AlarmIntentParams.DATE_FORMAT).parseLocalDate(dateStr);
    } else {
        Log.w(TAG, "Date not supplied, assuming today.");
        date = LocalDate.now();
    }
    switch(action) {
        case CalendulaApp.ACTION_CANCEL_ROUTINE:
            routineId = intent.getLongExtra(CalendulaApp.INTENT_EXTRA_ROUTINE_ID, -1);
            if (routineId != -1) {
                AlarmScheduler.instance().onIntakeCancelled(Routine.findById(routineId), date, context);
                Toast.makeText(context, context.getString(R.string.reminder_cancelled_message), Toast.LENGTH_SHORT).show();
            }
            break;
        case CalendulaApp.ACTION_CANCEL_HOURLY_SCHEDULE:
            scheduleId = intent.getLongExtra(CalendulaApp.INTENT_EXTRA_SCHEDULE_ID, -1);
            scheduleTime = intent.getStringExtra(CalendulaApp.INTENT_EXTRA_SCHEDULE_TIME);
            if (scheduleId != -1 && scheduleTime != null) {
                LocalTime t = DateTimeFormat.forPattern("kk:mm").parseLocalTime(scheduleTime);
                AlarmScheduler.instance().onIntakeCancelled(Schedule.findById(scheduleId), t, date, context);
                Toast.makeText(context, context.getString(R.string.reminder_cancelled_message), Toast.LENGTH_SHORT).show();
            }
            break;
        default:
            Log.d(TAG, "Request not handled " + intent.toString());
            break;
    }
}
Example 95
Project: crowdsource-master  File: ProjectDetailPage.java View source code
public List<Comment> comments() {
    final org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yy HH:mm");
    return comments.findElements(By.className("comment")).stream().map( commentElement -> {
        final String userName = commentElement.findElement(By.className("comment-user")).getText();
        final String commentText = commentElement.findElement(By.className("comment-comment")).getText();
        final DateTime createdDate = DateTime.parse(commentElement.findElement(By.className("comment-date")).getText(), formatter);
        return new Comment(createdDate, userName, commentText);
    }).collect(Collectors.toList());
}
Example 96
Project: D-MARLA-master  File: IllegalInstantException.java View source code
private static String createMessage(long instantLocal, String zoneId) {
    String localDateTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").print(new Instant(instantLocal));
    String zone = (zoneId != null ? " (" + zoneId + ")" : "");
    return "Illegal instant due to time zone offset transition (daylight savings time 'gap'): " + localDateTime + zone;
}
Example 97
Project: Dials-master  File: DateRangeFeatureFilter.java View source code
@Override
public void dial(ContextualMessage message, String filterName) {
    FeatureModel feature = message.getFeature();
    DialHelper helper = new DialHelper(feature.getFilter(filterName).getDial());
    String dialPattern = helper.getDialPattern(message);
    if (dialPattern.equals(DialHelper.ATTEMPTED)) {
        message.performDialAdjustment(feature.getFeatureName(), filterName, END_DATE, DateTimeFormat.forPattern("yyyy-MM-dd").print(endDate));
        return;
    }
    Integer daysToAdd = consumeDialPattern(dialPattern);
    if (daysToAdd != null) {
        message.getExecutionContext().addExecutionStep("Dial with pattern " + dialPattern + " performed on " + getClass().getSimpleName());
        endDate = endDate.plusDays(daysToAdd);
        message.performDialAdjustment(feature.getFeatureName(), filterName, END_DATE, DateTimeFormat.forPattern("yyyy-MM-dd").print(endDate));
        message.getExecutionContext().addExecutionStep("Dial successfully executed. New end date is " + endDate);
        if (endDate.isBeforeNow()) {
            message.disableFeature(feature.getFeatureName());
            message.getExecutionContext().addExecutionStep("End date is now surpassed, disabling feature.");
        }
    }
}
Example 98
Project: eGov-master  File: UserAdapter.java View source code
@Override
public JsonElement serialize(Citizen citizen, Type type, JsonSerializationContext context) {
    JsonObject jo = new JsonObject();
    if (citizen.getName() != null)
        jo.addProperty("name", citizen.getName());
    jo.addProperty("emailId", citizen.getEmailId());
    jo.addProperty("mobileNumber", citizen.getMobileNumber());
    jo.addProperty("userName", citizen.getUsername());
    if (citizen.getAltContactNumber() != null)
        jo.addProperty("altContactNumber", citizen.getAltContactNumber());
    if (citizen.getGender() != null)
        jo.addProperty("gender", citizen.getGender().name());
    if (citizen.getPan() != null)
        jo.addProperty("pan", citizen.getPan());
    if (citizen.getDob() != null) {
        DateTimeFormatter ft = DateTimeFormat.forPattern("yyyy-MM-dd");
        jo.addProperty("dob", ft.print(citizen.getDob().getTime()));
    }
    if (citizen.getAadhaarNumber() != null)
        jo.addProperty("aadhaarNumber", citizen.getAadhaarNumber());
    if (citizen.getLocale() != null)
        jo.addProperty("preferredLanguage", citizen.getLocale());
    return jo;
}
Example 99
Project: elastic-compass-master  File: DataTimeConverter.java View source code
public Formatter create() {
    if (ISO.equalsIgnoreCase(format)) {
        return new DateTimeFormatter(ISODateTimeFormat.dateTime());
    }
    org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
    formatter = formatter.withLocale(locale);
    return new DateTimeFormatter(formatter);
}
Example 100
Project: financius-master  File: BaseInterval.java View source code
public static String getTitle(Context context, Interval interval, Type type) {
    switch(type) {
        case DAY:
            return DateTimeFormat.mediumDate().print(interval.getStart());
        case WEEK:
            return DateUtils.formatDateTime(context, interval.getStart(), DateUtils.FORMAT_ABBREV_ALL) + " - " + DateUtils.formatDateTime(context, interval.getEnd().minusMillis(1), DateUtils.FORMAT_ABBREV_ALL);
        case MONTH:
            return DateUtils.formatDateTime(context, interval.getStart(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY);
        case YEAR:
            return interval.getStart().year().getAsText();
        default:
            throw new IllegalArgumentException("Type " + type + " is not supported.");
    }
}
Example 101
Project: financius-public-master  File: BaseInterval.java View source code
public static String getTitle(Context context, Interval interval, Type type) {
    switch(type) {
        case DAY:
            return DateTimeFormat.mediumDate().print(interval.getStart());
        case WEEK:
            return DateUtils.formatDateTime(context, interval.getStart(), DateUtils.FORMAT_ABBREV_ALL) + " - " + DateUtils.formatDateTime(context, interval.getEnd().minusMillis(1), DateUtils.FORMAT_ABBREV_ALL);
        case MONTH:
            return DateUtils.formatDateTime(context, interval.getStart(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY);
        case YEAR:
            return interval.getStart().year().getAsText();
        default:
            throw new IllegalArgumentException("Type " + type + " is not supported.");
    }
}