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


Java DateTimeFormatter类代码示例

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


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

示例1: main

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
public static void main(String ... args) {

        List<String> strings = Arrays.asList("Hello", "World!", "From: ",
              InetAddress.getLoopbackAddress().toString());

        String helloWorld = strings.parallelStream()
              .map(s -> s.toLowerCase(Locale.ROOT))
              .collect(joining(","));

        Stream.of(helloWorld.split(","))
              .forEach(System.out::println);

        String newDate = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(
                LocalDateTime.now(ZoneId.of("GMT")));

        String oldDate = String.format("%s%n",
                DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.ROOT)
                        .format(new Date()));

        LOGGER.log(Level.INFO, "New Date: " + newDate + " - old: " + oldDate);
    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:HelloClasslist.java

示例2: registerFormatters

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
@Override
public void registerFormatters(FormatterRegistry registry) {
	DateTimeConverters.registerConverters(registry);

	DateTimeFormatter dateFormatter = getFormatter(Type.DATE);
	DateTimeFormatter timeFormatter = getFormatter(Type.TIME);
	DateTimeFormatter dateTimeFormatter = getFormatter(Type.DATE_TIME);

	registry.addFormatterForFieldType(LocalDate.class,
			new TemporalAccessorPrinter(dateFormatter),
			new TemporalAccessorParser(LocalDate.class, dateFormatter));

	registry.addFormatterForFieldType(LocalTime.class,
			new TemporalAccessorPrinter(timeFormatter),
			new TemporalAccessorParser(LocalTime.class, timeFormatter));

	registry.addFormatterForFieldType(LocalDateTime.class,
			new TemporalAccessorPrinter(dateTimeFormatter),
			new TemporalAccessorParser(LocalDateTime.class, dateTimeFormatter));

	registry.addFormatterForFieldType(ZonedDateTime.class,
			new TemporalAccessorPrinter(dateTimeFormatter),
			new TemporalAccessorParser(ZonedDateTime.class, dateTimeFormatter));

	registry.addFormatterForFieldType(OffsetDateTime.class,
			new TemporalAccessorPrinter(dateTimeFormatter),
			new TemporalAccessorParser(OffsetDateTime.class, dateTimeFormatter));

	registry.addFormatterForFieldType(OffsetTime.class,
			new TemporalAccessorPrinter(timeFormatter),
			new TemporalAccessorParser(OffsetTime.class, timeFormatter));

	registry.addFormatterForFieldType(Instant.class, new InstantFormatter());

	registry.addFormatterForFieldAnnotation(new Jsr310DateTimeFormatAnnotationFormatterFactory());
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:37,代码来源:DateTimeFormatterRegistrar.java

示例3: createDefectLog

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
public static DefectLog createDefectLog(LocalDateTime date, int number, PSP.Defect type, PSP.Phase inject, PSP.Phase remove, int fixMin, int reference, String description) {
  refresh();
	Element element = new Element(DefectLog.ELEMENT_NAME);
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DefectLog.DATE_FORMAT);
	element.addAttribute(new Attribute(DefectLog.ID_ELEMENT, Util.generateId()));
	element.addAttribute(new Attribute(DefectLog.DATE_ELEMENT, date.format(formatter)));
	element.addAttribute(new Attribute(DefectLog.NUMBER_ELEMENT, String.valueOf(number)));
	element.addAttribute(new Attribute(DefectLog.TYPE_ELEMENT, type.toString()));
	element.addAttribute(new Attribute(DefectLog.INJECT_ELEMENT, inject.toString()));
	element.addAttribute(new Attribute(DefectLog.REMOVE_ELEMENT, remove.toString()));
	element.addAttribute(new Attribute(DefectLog.FIX_ELEMENT, String.valueOf(fixMin)));
	element.addAttribute(new Attribute(DefectLog.REFERENCE_ELEMENT, String.valueOf(reference)));
	element.addAttribute(new Attribute(DefectLog.DESCRIPTION_ELEMENT, description));
	element.appendChild(description);
	Day d = getDay(date);
	
	if (d == null)
		d = createDay(date);
	
	d.getElement().appendChild(element);
	return new DefectLog(element);
}
 
开发者ID:ser316asu,项目名称:Neukoelln_SER316,代码行数:23,代码来源:DefectLogManager.java

示例4: testParsingCustomFormatterStringToDate

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test
public final void testParsingCustomFormatterStringToDate() {
    MatcherAssert.assertThat(
        "Can't parse a Date with custom format.",
        new DateOf(
            "2017-12-13 14:15:16.000000017",
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.n")
        ).value(),
        Matchers.is(
            Date.from(
                LocalDateTime.of(
                    2017, 12, 13, 14, 15, 16, 17
                ).toInstant(ZoneOffset.UTC)
            )
        )
    );
}
 
开发者ID:yegor256,项目名称:cactoos,代码行数:18,代码来源:DateOfTest.java

示例5: testSetters

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test
public void testSetters() throws Exception {
	String timeValue = "2000-12-01 12:55";
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
	LocalDateTime timeStart = LocalDateTime.parse(timeValue, formatter);
	LocalDateTime timeStop = timeStart.plusMinutes(90);
	PSP.Phase phase = PSP.Phase.PostMortem;
	int interruption = 30;
	String comments = "this is a test";
	testLog.setTimeStart(timeStart);
	testLog.setTimeStop(timeStop);
	testLog.setInterruptionMin(interruption);
	testLog.setPhase(phase);
	testLog.setComments(comments);
	Assert.assertEquals(timeStart, testLog.getTimeStart());
	Assert.assertEquals(timeStop, testLog.getTimeStop());
	Assert.assertEquals(interruption, testLog.getInterruptionMin());
	Assert.assertEquals(phase, testLog.getPhase());
	Assert.assertEquals(comments, testLog.getComments());
}
 
开发者ID:ser316asu,项目名称:Neukoelln_SER316,代码行数:21,代码来源:TimeLogTest.java

示例6: parseTime

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
private ZonedDateTime parseTime(String time) {
  // TODO : may support more than one format at some point
  DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
      .withZone(ZoneId.systemDefault());
  ZonedDateTime zdt = null;

  try {
    zdt = ZonedDateTime.parse(time, dtf);
  } catch (DateTimeParseException e) {
    logger.debug("parseTime() failed to parse '" + time + "'");
    // throw an exception
    // mark as complete (via max iterations?)
  }

  return zdt;
}
 
开发者ID:edgexfoundry,项目名称:device-bluetooth,代码行数:17,代码来源:ScheduleContext.java

示例7: getRegisterDate

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
/**
 * Help Command
 *
 * @param event MessageEvent
 * @param args  Argumente [Not needed]
 * @return state
 */
@Command(
        command = "getregister",
        description = "Display the help",
        alias = "greg",
        arguments = {"Mention User []"},
        permission = Globals.BOT_INFO,
        prefix = Globals.INFO_PREFIX
)
public boolean getRegisterDate(MessageReceivedEvent event, String[] args) {
    new Thread(() -> {
        StringBuilder content = new StringBuilder();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy H:m:s");
        if (event.getMessage().getMentions().size() > 0) {
            for (IUser user : event.getMessage().getMentions()) {
                content.append(user.getName()).append(":  ").append(user.getCreationDate().format(formatter)).append("\n");
            }
        } else {
            content.append("No User specified");
        }
        BotUtils.sendMessage(event.getChannel(), content.toString(), false);
    }).start();
    return true;
}
 
开发者ID:ModdyLP,项目名称:MoMuOSB,代码行数:31,代码来源:InfoCommands.java

示例8: generateDS1

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
private DataSet<Movie, Attribute> generateDS1() {
	DataSet<Movie, Attribute> ds = new HashedDataSet<>();
	DateTimeFormatter formatter = new DateTimeFormatterBuilder()
	        .appendPattern("yyyy-MM-dd")
	        .parseDefaulting(ChronoField.CLOCK_HOUR_OF_DAY, 0)
	        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
	        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
	        .toFormatter(Locale.ENGLISH);
	
	Movie m1 = new Movie("1", "DS1");
	m1.setDate(LocalDateTime.parse("1980-10-10", formatter));
	ds.add(m1);
	Movie m2 = new Movie("2", "DS1");
	m2.setDate(LocalDateTime.parse("1990-10-10", formatter));
	ds.add(m2);
	Movie m3 = new Movie("3", "DS1");
	m3.setDate(LocalDateTime.parse("1991-10-10", formatter));
	ds.add(m3);
	return ds;
}
 
开发者ID:olehmberg,项目名称:winter,代码行数:21,代码来源:SortedNeighbourhoodBlockerTest.java

示例9: redraw

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
private void redraw() {
    ctx.clearRect(0, 0, width, height);
    paths.forEach((path, plotItem) -> path.draw(ctx, true, true));
    Color             textColor      = getTextColor();
    int               noOfCategories = chartItems.size();
    DateTimeFormatter formatter      = getCategory().formatter();

    for (int category = 0 ; category < noOfCategories ; category++) {
        List<ChartItemData> itemDataInCategory = itemsPerCategory.get(category);

        // Go through all item data of the current category
        for (ChartItemData itemData : itemDataInCategory) {
            ChartItem item      = itemData.getChartItem();
            CtxBounds bounds    = itemData.getBounds();
            Color     itemColor = item.getFill();

            // Draw item boxes with their labels
            ctx.setFill(itemColor);
            ctx.fillRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight());
            ctx.setLineWidth(0);
            ctx.setStroke(itemColor);
            ctx.strokeRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight());

            if (item.getValue() > 1) {
                ctx.setFill(textColor);
                ctx.setTextAlign(category == noOfCategories ? TextAlignment.RIGHT : TextAlignment.LEFT);
                ctx.fillText(item.getName(), itemData.getTextPoint().getX(), itemData.getTextPoint().getY(), bounds.getWidth());
            }
        }
        // Draw category text
        ChartItemData firstItem = itemDataInCategory.get(0);
        ctx.fillText(formatter.format(firstItem.getLocalDate()), firstItem.getTextPoint().getX(), reducedHeight + size * 0.02, firstItem.bounds.getWidth());
    }
}
 
开发者ID:HanSolo,项目名称:charts,代码行数:35,代码来源:StreamChart.java

示例10: action

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
@Override
public void action(String prefix, String[] args, MessageReceivedEvent event)
{
    int index = 0;
    Integer entryId = ParsingUtilities.encodeIDToInt(args[index++]);
    ScheduleEntry se = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());

    // send a confirmation to the channel
    String content;
    if(se.getRecurrence().shouldRepeat(se.getStart()))
    {
        se.repeat();
        content = "The event has been cancelled.\n" +
                "The event is next scheduled for " +
                se.getStart().format(DateTimeFormatter.ofPattern("MMM d, hh:mm a"));
    }
    else
    {
        se.repeat();
        content = "The event has been cancelled.";
    }
    MessageUtilities.sendMsg(content, event.getTextChannel(), null);
}
 
开发者ID:notem,项目名称:Saber-Bot,代码行数:24,代码来源:SkipCommand.java

示例11: FromString

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
public static PIMTodo FromString(String s)
{
    //s likes "Type: PIMTodo    Priority: normal    Date: 2017-04-20    text""
    String[] ss = s.split("(Type: )|(Priority: )|(Date: )|(    )");
    String[] sss = new String[4];
    int temp = 0;
    for (String var : ss) {
        if(temp >= 4){
            System.out.println("Input String can't to PIMTodo.");
            return null;
        }
        if(!var.equals("")){
            sss[temp] = var;
            temp ++;
        }
    }
    if(!sss[0].equals("PIMTodo")){
        System.out.println("Input String can't to PIMTodo.");
        return null;
    }

    return new PIMTodo(sss[3], LocalDate.parse(sss[2],DateTimeFormatter.ofPattern("yyyy-MM-dd")), sss[1]);
}
 
开发者ID:starsriver,项目名称:JavaHomework,代码行数:24,代码来源:PIMTodo.java

示例12: bepaalPersoonIds

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
@Bedrijfsregel(Regel.R2402)
private List<Long> bepaalPersoonIds(final Set<ZoekCriterium> zoekCriteria, final Integer maxAantalZoekResultaten,
                                    final ZoekPersoonGeneriekVerzoek.ZoekBereikParameters zoekBereikParameters)
        throws StapMeldingException, QueryNietUitgevoerdException {
    final List<Long> persoonIds;
    final boolean historisch = zoekBereikParameters != null && (zoekBereikParameters.getPeilmomentMaterieel() != null || Zoekbereik.MATERIELE_PERIODE
            .equals(zoekBereikParameters.getZoekBereik()));
    if (historisch) {
        Integer peilmomentMaterieel = null;
        if (zoekBereikParameters.getPeilmomentMaterieel() != null) {
            peilmomentMaterieel = Integer.parseInt(
                    datumService.parseDate(zoekBereikParameters.getPeilmomentMaterieel()).format(DateTimeFormatter.BASIC_ISO_DATE));
        }
        persoonIds = zoekPersoonDataOphalerService
                .zoekPersonenHistorisch(zoekCriteria, peilmomentMaterieel,
                        Zoekbereik.MATERIELE_PERIODE.equals(zoekBereikParameters.getZoekBereik()), maxAantalZoekResultaten);
    } else {
        persoonIds = zoekPersoonDataOphalerService.zoekPersonenActueel(zoekCriteria, maxAantalZoekResultaten);
    }
    return persoonIds;
}
 
开发者ID:MinBZK,项目名称:OperatieBRP,代码行数:22,代码来源:AbstractZoekPersoonOphalenPersoonServiceImpl.java

示例13: parseTime

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
private ZonedDateTime parseTime(String time) {
  // TODO : may support more than one format at some point
  DateTimeFormatter dtf =
      DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0]).withZone(ZoneId.systemDefault());
  ZonedDateTime zdt = null;

  try {
    zdt = ZonedDateTime.parse(time, dtf);
  } catch (DateTimeParseException e) {
    logger.debug("parseTime() failed to parse '" + time + "'");
    // throw an exception
    // mark as complete (via max iterations?)
  }

  return zdt;
}
 
开发者ID:mgjeong,项目名称:device-opcua-java,代码行数:17,代码来源:ScheduleContext.java

示例14: test_resolveThreeToDate

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test(dataProvider="resolveThreeToDate")
public void test_resolveThreeToDate(TemporalField field1, long value1,
                                  TemporalField field2, long value2,
                                  TemporalField field3, long value3,
                                  LocalDate expectedDate) {
    String str = value1 + " " + value2 + " " + value3;
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(field1).appendLiteral(' ')
            .appendValue(field2).appendLiteral(' ')
            .appendValue(field3).toFormatter();

    TemporalAccessor accessor = f.parse(str);
    assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate);
    assertEquals(accessor.query(TemporalQueries.localTime()), null);
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:16,代码来源:TCKDateTimeParseResolver.java

示例15: test_parse_CharSequence_ParsePosition_parseError

import java.time.format.DateTimeFormatter; //导入依赖的package包/类
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parse_CharSequence_ParsePosition_parseError() {
    DateTimeFormatter test = DateTimeFormatter.ISO_DATE;
    ParsePosition pos = new ParsePosition(3);
    try {
        test.parse("XXX2012XXX", pos);
        fail();
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getErrorIndex(), 7);
        throw ex;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:TCKDateTimeFormatter.java


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