當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。