当前位置: 首页>>代码示例>>Java>>正文


Java DateTimeFormatter类代码示例

本文整理汇总了Java中org.joda.time.format.DateTimeFormatter的典型用法代码示例。如果您正苦于以下问题:Java DateTimeFormatter类的具体用法?Java DateTimeFormatter怎么用?Java DateTimeFormatter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DateTimeFormatter类属于org.joda.time.format包,在下文中一共展示了DateTimeFormatter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: dateSearchBraces

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test
 public void dateSearchBraces() throws IOException, SqlParseException, SQLFeatureNotSupportedException, ParseException {
     DateTimeFormatter formatter = DateTimeFormat.forPattern(TS_DATE_FORMAT);
     DateTime dateToCompare = new DateTime(2015, 3, 15, 0, 0, 0);

     SearchHits response = query(String.format("SELECT odbc_time FROM %s/odbc WHERE odbc_time < {ts '2015-03-15 00:00:00.000'}", TEST_INDEX));
     SearchHit[] hits = response.getHits();
     for(SearchHit hit : hits) {
         Map<String, Object> source = hit.getSource();
String insertTimeStr = (String) source.get("odbc_time");
insertTimeStr = insertTimeStr.replace("{ts '", "").replace("'}", "");

         DateTime insertTime = formatter.parseDateTime(insertTimeStr);

         String errorMessage = String.format("insert_time must be smaller then 2015-03-15. found: %s", insertTime);
         Assert.assertTrue(errorMessage, insertTime.isBefore(dateToCompare));
     }
 }
 
开发者ID:mazhou,项目名称:es-sql,代码行数:19,代码来源:QueryTest.java

示例2: getSingleItemDescription

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
@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)) {
        int dayOfWeekNum = Integer.parseInt(exp);
        boolean isZeroBasedDayOfWeek = (options == null || options.isZeroBasedDayOfWeek());
        boolean isInvalidDayOfWeekForSetting = (options != null && !options.isZeroBasedDayOfWeek() && dayOfWeekNum <= 1);
        if (isInvalidDayOfWeekForSetting || (isZeroBasedDayOfWeek && dayOfWeekNum == 0)) {
            return DateAndTimeUtils.getDayOfWeekName(7);
        } else if (options != null && !options.isZeroBasedDayOfWeek()) {
            dayOfWeekNum -= 1;
        }
        return DateAndTimeUtils.getDayOfWeekName(dayOfWeekNum);
    } else {
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH);
        return dateTimeFormatter.parseDateTime(WordUtils.capitalizeFully(exp)).dayOfWeek().getAsText(I18nMessages.getCurrentLocale());
    }
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:24,代码来源:DayOfWeekDescriptionBuilder.java

示例3: getYearsBetween

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
public static int getYearsBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Years.yearsBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getYears();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
 
开发者ID:Suhas010,项目名称:Artificial-Intelligent-chat-bot-,代码行数:18,代码来源:IntervalUtils.java

示例4: getExecCommandForHeapDump

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
/**
 * Generate parameters for JVM Heap dump
 *
 * @param scriptName
 * @param jvm
 * @return
 */
private ExecCommand getExecCommandForHeapDump(String scriptName, Jvm jvm) {
    final String trimmedJvmName = StringUtils.deleteWhitespace(jvm.getJvmName());

    final String jvmRootDir = Paths.get(jvm.getTomcatMedia().getRemoteDir().toString() + '/' + trimmedJvmName + '/' +
            jvm.getTomcatMedia().getRootDir()).normalize().toString();

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd.HHmmss");
    final String dumpFile = "heapDump." + trimmedJvmName + "." + formatter.print(DateTime.now());

    final String dumpLiveStr = ApplicationProperties.getAsBoolean(PropertyKeys.JMAP_DUMP_LIVE_ENABLED.name()) ? "live," : "\"\"";

    final String heapDumpDir = jvm.getTomcatMedia().getRemoteDir().normalize().toString() + "/" + jvm.getJvmName();

    return new ExecCommand(getFullPathScript(jvm, scriptName), jvm.getJavaHome(), heapDumpDir, dumpFile,
                           dumpLiveStr , jvmRootDir, jvm.getJvmName());
}
 
开发者ID:cerner,项目名称:jwala,代码行数:24,代码来源:JvmCommandFactory.java

示例5: checkStateAndLogIfNecessary

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
void checkStateAndLogIfNecessary() {
  if (!fragmentStarted) {
    final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    if (isCancelled()) {
      logger.warn("Received cancel request at {} for fragment {} that was never started",
        formatter.print(cancellationTime),
        QueryIdHelper.getQueryIdentifier(handle));
    }

    FragmentEvent event;
    while ((event = finishedReceivers.poll()) != null) {
      logger.warn("Received early fragment termination at {} for path {} {} -> {} for a fragment that was never started",
        formatter.print(event.time),
        QueryIdHelper.getQueryId(handle.getQueryId()),
        QueryIdHelper.getFragmentId(event.handle),
        QueryIdHelper.getFragmentId(handle)
      );
    }
  }
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:21,代码来源:FragmentHandler.java

示例6: testJoda

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test
public void testJoda()
{
	DateTimeFormatter format = DateTimeFormat .forPattern("yyyy-MM-dd HH:mm:ss");    
       //时间解析      
       DateTime dateTime2 = DateTime.parse("2012-12-21 23:22:45", format);      
             
       //时间格式化,输出==> 2012/12/21 23:22:45 Fri      
       String string_u = dateTime2.toString("yyyy/MM/dd HH:mm:ss EE");      
       System.out.println(string_u);      
             
       //格式化带Locale,输出==> 2012年12月21日 23:22:45 星期五      
       String string_c = dateTime2.toString("yyyy年MM月dd日 HH:mm:ss EE",Locale.CHINESE);      
       System.out.println(string_c);    
       
       LocalDate date = LocalDate.parse("2012-12-21 23:22:45", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
       Date dates = date.toDate();
       System.out.println(dates);
            
}
 
开发者ID:wjggwm,项目名称:webside,代码行数:21,代码来源:TestJoda.java

示例7: testDate

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
public void testDate() throws Exception {
    assertResult("{'date':null}", () -> builder().startObject().field("date", (Date) null).endObject());
    assertResult("{'date':null}", () -> builder().startObject().field("date").value((Date) null).endObject());

    final Date d1 = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC).toDate();
    assertResult("{'d1':'2016-01-01T00:00:00.000Z'}", () -> builder().startObject().field("d1", d1).endObject());
    assertResult("{'d1':'2016-01-01T00:00:00.000Z'}", () -> builder().startObject().field("d1").value(d1).endObject());

    final Date d2 = new DateTime(2016, 12, 25, 7, 59, 42, 213, DateTimeZone.UTC).toDate();
    assertResult("{'d2':'2016-12-25T07:59:42.213Z'}", () -> builder().startObject().field("d2", d2).endObject());
    assertResult("{'d2':'2016-12-25T07:59:42.213Z'}", () -> builder().startObject().field("d2").value(d2).endObject());

    final DateTimeFormatter formatter = randomFrom(ISODateTimeFormat.basicDate(), ISODateTimeFormat.dateTimeNoMillis());
    final Date d3 = DateTime.now().toDate();

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

    expectNonNullFormatterException(() -> builder().startObject().field("d3", d3, null).endObject());
    expectNonNullFormatterException(() -> builder().startObject().field("d3").value(d3, null).endObject());
    expectNonNullFormatterException(() -> builder().value(null, 1L));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:BaseXContentTestCase.java

示例8: getMonthsBetween

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
public static int getMonthsBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Months.monthsBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getMonths();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
 
开发者ID:Suhas010,项目名称:Artificial-Intelligent-chat-bot-,代码行数:18,代码来源:IntervalUtils.java

示例9: handleConfirmed

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
private SpeechletResponse handleConfirmed(IntentRequest request, Session session)
    throws CalendarWriteException {
  final String dateFormat = session.getAttribute(SESSION_DATE_FORMAT).toString();
  final DateTimeFormatter parser = DateTimeFormat.forPattern(dateFormat);
  final String title = collectSummary(request);
  final String calendar = session.getAttribute(SESSION_CALENDAR) != null ? session.getAttribute(SESSION_CALENDAR).toString() : null;
  final String from = session.getAttribute(SESSION_FROM).toString();
  final String to = session.getAttribute(SESSION_TO).toString();

  calendarService.createEvent(calendar, title,
      parser.parseDateTime(from),
      parser.parseDateTime(to));

  SimpleCard card = new SimpleCard();
  card.setTitle(messageService.de("event.new.card.title"));
  card.setContent(messageService.de("event.new.card.content", title, from, to));

  session.removeAttribute(BasicSpeechlet.KEY_DIALOG_TYPE);

  return SpeechletResponse.newTellResponse(
      speechService.speechNewEventSaved(request.getLocale()),
      card);
}
 
开发者ID:rainu,项目名称:alexa-skill,代码行数:24,代码来源:NewEventSpeechlet.java

示例10: getReportTableStartTime

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
private String getReportTableStartTime(JSONObject jsonObject, String endTime)
    throws ParseException {
  switch (jsonObject.getString(QueryHelper.PERIODICITY)) {
    case QueryHelper.PERIODICITY_MONTH:
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
      Calendar toDate = new GregorianCalendar();
      toDate.setTime(format.parse(endTime));
      toDate.add(Calendar.MONTH, -1*(QueryHelper.MONTHS_LIMIT-1));
      return format.format(toDate.getTime());
    case QueryHelper.PERIODICITY_WEEK:
      DateTimeFormatter mDateTimeFormatter = DateTimeFormat.forPattern(
          QueryHelper.DATE_FORMAT_DAILY);
      DateTime toTime = mDateTimeFormatter.parseDateTime(endTime);
      return mDateTimeFormatter.print(toTime.minusWeeks(QueryHelper.WEEKS_LIMIT-1));
    default:
      mDateTimeFormatter = DateTimeFormat.forPattern(QueryHelper.DATE_FORMAT_DAILY);
      toTime = mDateTimeFormatter.parseDateTime(endTime);
      return mDateTimeFormatter.print(toTime.minusDays(QueryHelper.DAYS_LIMIT-1));
  }
}
 
开发者ID:logistimo,项目名称:logistimo-web-service,代码行数:21,代码来源:ReportPluginService.java

示例11: onDateTimePicked

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
@Override
public void onDateTimePicked(DateTime d) {
    searchDateTime = d;

    DateTime now = new DateTime();

    DateTimeFormatter df = DateTimeFormat.forPattern("dd MMMM yyyy");
    DateTimeFormatter tf = DateTimeFormat.forPattern("HH:mm");

    String day = df.print(searchDateTime);
    String time = tf.print(searchDateTime);
    String at = getActivity().getResources().getString(R.string.time_at);

    if (now.get(DateTimeFieldType.year()) == searchDateTime.get(DateTimeFieldType.year())) {
        if (now.get(DateTimeFieldType.dayOfYear()) == searchDateTime.get(DateTimeFieldType.dayOfYear())) {
            day = getActivity().getResources().getString(R.string.time_today);
        } else  //noinspection RedundantCast
            if (now.get(DateTimeFieldType.dayOfYear()) + 1 == (int) searchDateTime.get(DateTimeFieldType.dayOfYear())) {
                day = getActivity().getResources().getString(R.string.time_tomorrow);
            }
    }
    vDatetime.setText(day + " " + at + " " + time);
}
 
开发者ID:hyperrail,项目名称:hyperrail-for-android,代码行数:24,代码来源:RouteSearchFragment.java

示例12: testDateRace

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test
public void testDateRace() {
  Clock mockClock = mock(Clock.class);
  DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
  long two = parser.parseMillis("2013-04-21T02:59:59-00:00");
  long three = parser.parseMillis("2013-04-21T03:00:00-00:00");
  when(mockClock.currentTimeMillis()).thenReturn(two, three);

  // save & modify static state (yuck)
  Clock origClock = BucketPath.getClock();
  BucketPath.setClock(mockClock);

  String pat = "%H:%M";
  String escaped = BucketPath.escapeString(pat,
      new HashMap<String, String>(),
      TimeZone.getTimeZone("UTC"), true, Calendar.MINUTE, 10, true);

  // restore static state
  BucketPath.setClock(origClock);

  Assert.assertEquals("Race condition detected", "02:50", escaped);
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:23,代码来源:TestBucketPath.java

示例13: testUnixTimeStampForDateWithPattern

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test
public void testUnixTimeStampForDateWithPattern() throws Exception {
  DateTimeFormatter formatter = DateFunctionsUtils.getFormatterForFormatString("YYYY-MM-DD HH:MI:SS.FFF");
  date = formatter.parseLocalDateTime("2009-03-20 11:30:01.0");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;

  testBuilder()
      .sqlQuery("select unix_timestamp('2009-03-20 11:30:01.0', 'YYYY-MM-DD HH:MI:SS.FFF') from cp.`employee.json` limit 1")
      .ordered()
      .baselineColumns("EXPR$0")
      .baselineValues(unixTimeStamp)
      .build().run();

  formatter = DateFunctionsUtils.getFormatterForFormatString("YYYY-MM-DD");
  date = formatter.parseLocalDateTime("2009-03-20");
  unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;

  testBuilder()
      .sqlQuery("select unix_timestamp('2009-03-20', 'YYYY-MM-DD') from cp.`employee.json` limit 1")
      .ordered()
      .baselineColumns("EXPR$0")
      .baselineValues(unixTimeStamp)
      .build().run();
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:25,代码来源:TestNewDateFunctions.java

示例14: testIsDate2

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test
public void testIsDate2() throws Exception {
  DateTimeFormatter formatter = DateFunctionsUtils.getFormatterForFormatString("YYYY-MM-DD");
  testBuilder()
      .sqlQuery("select case when isdate(date1) then cast(date1 as date) else null end res1 from " + dateValues)
      .unOrdered()
      .baselineColumns("res1")
      .baselineValues(formatter.parseLocalDateTime("1900-01-01"))
      .baselineValues(formatter.parseLocalDateTime("3500-01-01"))
      .baselineValues(formatter.parseLocalDateTime("2000-12-31"))
      .baselineValues(new Object[] {null})
      .baselineValues(new Object[] {null})
      .baselineValues(new Object[] {null})
      .build()
      .run();
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:17,代码来源:TestNewDateFunctions.java

示例15: formatDate

import org.joda.time.format.DateTimeFormatter; //导入依赖的package包/类
private void formatDate( String date, String datePattern ) {
    DateTimeFormatter customDateFormatter = DateTimeFormat.forPattern( datePattern );
    String dateString = date;
    if ( date != null ) {
        dateString = date;
        // dateString should already be padded with zeros before being parsed
        myDate = date == null ? null : LocalDate.parse( dateString, customDateFormatter );
        dt = dt.withDate( myDate.getYear(), myDate.getMonthOfYear(), myDate.getDayOfMonth() );
    }
}
 
开发者ID:dataloom,项目名称:integrations,代码行数:11,代码来源:FormattedDateTime.java


注:本文中的org.joda.time.format.DateTimeFormatter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。