项目:openjdk-jdk10
文件:HelloClasslist.java
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);
}
项目:Neukoelln_SER316
文件:DefectLogManager.java
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);
}
项目:cactoos
文件:DateOfTest.java
@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)
)
)
);
}
项目:Neukoelln_SER316
文件:TimeLogTest.java
@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());
}
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;
}
项目:MoMuOSB
文件:InfoCommands.java
/**
* 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;
}
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;
}
项目:charts
文件:StreamChart.java
private void redraw() {
ctx.clearRect(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.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());
}
}
项目:Saber-Bot
文件:SkipCommand.java
@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);
}
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]);
}
@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;
}
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;
}
项目:jdk8u-jdk
文件:TCKDateTimeParseResolver.java
@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);
}
项目:openjdk-jdk10
文件:TCKDateTimeFormatter.java
@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;
}
}
项目:Saber-Bot
文件:Logging.java
/**
* used logging minor (possibly expected) errors (level 2)
* @param caller the java class from which the command is called
* @param msg the message to log
*/
public static void warn(Class caller,String msg)
{
if(Main.getBotSettingsManager().getLogLevel() < 2) return;
String Now = LocalTime.Now().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_LOCAL_TIME);
String content = "[" + Now + "] " +
ANSI_RED + "[Warn]" + ANSI_RESET + " " +
ANSI_YELLOW_BACKGROUND + ANSI_BLACK +
"[" + caller.getSimpleName() + "]" +
ANSI_RESET + " " + ANSI_RED + msg +
ANSI_RESET;
System.out.println(content);
}
项目:swallow-core
文件:DateUtils.java
/**
* 格式化日期
*
* @param localDateTime 日期
* @param pattern 日期格式
* @return 格式化后的日期字符串
*/
public static String format(LocalDateTime localDateTime,String pattern) {
Objects.requireNonNull(localDateTime,"localDateTime is null.");
try {
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
} catch (Exception e) {
throw new SwallowException("pattern is incorrect.",e);
}
}
项目:java-velocypack-module-jdk8
文件:VPackTimeTest.java
@Test
public void offsetDateTimeCompatibilityWithDateTimeFormatter() throws Exception {
final OffsetDateTime out = OffsetDateTime.Now();
final String s = out.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
final OffsetDateTime in = VPackJdk8Deserializers.OFFSET_DATE_TIME.deserialize(null,new VPackBuilder().add(s).slice(),null);
assertthat(in,is(out));
}
项目:openjdk-jdk10
文件:TCKDateTimeFormatters.java
@Test(dataProvider="sample_isoOffsetDate")
public void test_parse_isoOffsetDate(
Integer year,Integer month,Integer day,String offsetId,String zoneId,String input,Class<?> invalid) {
if (input != null) {
Expected expected = createDate(year,month,day);
buildCalendrical(expected,offsetId,null); // zone not expected to be parsed
assertParseMatch(DateTimeFormatter.ISO_OFFSET_DATE.parseUnresolved(input,new ParsePosition(0)),expected);
}
}
项目:jdk8u-jdk
文件:TCKDateTimeParseResolver.java
@Test
public void test_fieldResolvestochronoLocalDateTime_overrideChrono_matches() {
MinguoDate mdt = MinguoDate.of(100,6,30);
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(mdt.atTime(LocalTime.NOON))).toFormatter();
f = f.withChronology(MinguoChronology.INSTANCE);
TemporalAccessor accessor = f.parse("1234567890");
assertEquals(accessor.query(TemporalQueries.localDate()),LocalDate.from(mdt));
assertEquals(accessor.query(TemporalQueries.localTime()),LocalTime.NOON);
assertEquals(accessor.query(TemporalQueries.chronology()),MinguoChronology.INSTANCE);
}
项目:jdk8u-jdk
文件:TCKIsoFields.java
@Test(dataProvider="week")
public void test_parse_weeks_SMART(LocalDate date,DayOfWeek dow,int week,int wby) {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral('-')
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral('-')
.appendValue(DAY_OF_WEEK)
.toFormatter().withResolverStyle(ResolverStyle.SMART);
LocalDate parsed = LocalDate.parse(wby + "-" + week + "-" + dow.getValue(),f);
assertEquals(parsed,date);
}
项目:wall-t
文件:TileView.java
private HBox createLastBuildInfoBox( final Tileviewmodel build ) {
final HBox lastBuildInfoPart = new HBox( );
lastBuildInfoPart.setAlignment( Pos.CENTER );
final ImageView lastBuildIcon = new ImageView( UIUtils.createImage( "icons/lastBuild.png" ) );
lastBuildIcon.setPreserveRatio( true );
lastBuildIcon.setFitWidth( 32 );
final Label lastBuildDate = new Label( );
lastBuildDate.setMinWidth( 110 );
lastBuildDate.setTextAlignment( CENTER );
lastBuildDate.setAlignment( Pos.CENTER );
lastBuildDate.setFont( UIUtils.font( 32,FontWeight.BOLD ) );
lastBuildDate.setTextFill( Color.WHITE );
lastBuildDate.setWrapText( true );
lastBuildDate.setLinespacing( 2 ); // Todo: Seems do not work
lastBuildDate.setEffect( UIUtils.shadowEffect( ) );
lastBuildDate.textProperty( ).bind( createStringBinding( ( ) -> {
final LocalDateTime localDateTime = build.lastFinishedDateProperty( ).get( );
if ( localDateTime == null )
return "00/00\n00:00";
return localDateTime.format( DateTimeFormatter.ofPattern( "dd/MM\nHH:mm" ) );
},build.lastFinishedDateProperty( ) ) );
lastBuildInfoPart.getChildren( ).addAll( lastBuildIcon,lastBuildDate );
return lastBuildInfoPart;
}
项目:openjdk-jdk10
文件:TestDateTimeFormatterBuilder.java
@Test(dataProvider="offsetPatterns")
public void test_appendOffset_format(String pattern,int h,int m,int s,String expected) throws Exception {
builder.appendOffset(pattern,"Z");
DateTimeFormatter f = builder.toFormatter();
ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(h,m,s);
assertEquals(f.format(offset),expected);
}
项目:jdk8u-jdk
文件:TCKDateTimeParseResolver.java
@Test
public void test_withChronology_parsedChronology_noOverride() {
DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY,2).appendChronologyId().toFormatter();
TemporalAccessor accessor = f.parse("ThaiBuddhist");
assertEquals(accessor.query(TemporalQueries.localDate()),LocalDate.of(1970,1,3));
assertEquals(accessor.query(TemporalQueries.localTime()),null);
assertEquals(accessor.query(TemporalQueries.chronology()),ThaiBuddhistChronology.INSTANCE);
}
项目:openjdk-jdk10
文件:TCKDateTimeFormatters.java
@Test(dataProvider="sample_isoInstant")
public void test_parse_isoInstant(
long instantSecs,Integer nano,Class<?> invalid) {
if (input != null) {
TemporalAccessor parsed = DateTimeFormatter.ISO_INSTANT.parseUnresolved(input,new ParsePosition(0));
assertEquals(parsed.getLong(INSTANT_SECONDS),instantSecs);
assertEquals(parsed.getLong(NANO_OF_SECOND),(nano == null ? 0 : nano));
}
}
项目:apollo-custom
文件:ServiceExceptionTest.java
@Test
public void testAdminServiceException() {
String errorMsg = "No available admin service";
String errorCode = "errorCode";
String status = "500";
Map<String,Object> errorAttributes = new LinkedHashMap<>();
errorAttributes.put("status",status);
errorAttributes.put("message",errorMsg);
errorAttributes.put("timestamp",LocalDateTime.Now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
errorAttributes.put("exception",ServiceException.class.getName());
errorAttributes.put("errorCode",errorCode);
HttpStatusCodeException adminexception =
new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR,"admin server error",new Gson().toJson(errorAttributes).getBytes(),Charset.defaultCharset());
when(appService.createAppInLocal(any())).thenThrow(adminexception);
AppModel app = generateSampleApp();
try {
appController.create(app);
} catch (HttpStatusCodeException e) {
@SuppressWarnings("unchecked")
Map<String,String> attr = new Gson().fromJson(e.getResponseBodyAsstring(),Map.class);
Assert.assertEquals(errorMsg,attr.get("message"));
Assert.assertEquals(errorCode,attr.get("errorCode"));
Assert.assertEquals(status,attr.get("status"));
}
}
项目:lams
文件:DateTimeFormatterRegistrar.java
@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 TemporalAccessorParser(zoneddatetime.class,dateTimeFormatter));
registry.addFormatterForFieldType(OffsetDateTime.class,new TemporalAccessorParser(OffsetDateTime.class,dateTimeFormatter));
registry.addFormatterForFieldType(OffsetTime.class,new TemporalAccessorParser(OffsetTime.class,timeFormatter));
registry.addFormatterForFieldType(Instant.class,new InstantFormatter());
registry.addFormatterForFieldAnnotation(new jsr310DateTimeFormatannotationFormatterFactory());
}
项目:openjdk-jdk10
文件:TCKDateTimeParseResolver.java
@Test(dataProvider="resolveOnetoTime")
public void test_resolveOnetoTime(TemporalField field1,LocalTime expectedTime) {
String str = Long.toString(value1);
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter();
TemporalAccessor accessor = f.parse(str);
assertEquals(accessor.query(TemporalQueries.localDate()),null);
assertEquals(accessor.query(TemporalQueries.localTime()),expectedTime);
}
项目:GitHub
文件:Issue1493.java
public void test_for_issue() throws Exception {
TestBean test = new TestBean();
String stime2 = "2017-09-22 15:08:56";
LocalDateTime time1 = LocalDateTime.Now();
time1 = time1.minusNanos(10L);
System.out.println(time1.getNano());
LocalDateTime time2 = LocalDateTime.parse(stime2,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss",Locale.CHINA));
test.setTime1(time1);
test.setTime2(time2);
String t1 = JSON.toJSONString(time1,SerializerFeature.WriteDateUseDateFormat);
String json = JSON.toJSONString(test,SerializerFeature.WriteDateUseDateFormat);
Assert.assertEquals("{\"time1\":"+t1+",\"time2\":\""+stime2+"\"}",json);
//String default_format = JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT;
//JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//String stime1 = DateTimeFormatter.ofPattern(JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT,Locale.CHINA).format(time1);
json = JSON.toJSONString(test,SerializerFeature.WriteDateUseDateFormat);
Assert.assertEquals("{\"time1\":"+ JSON.toJSONString(time1,SerializerFeature.WriteDateUseDateFormat) +",json);
String pattern = "yyyy-MM-dd HH:mm:ss";
String stime1 = DateTimeFormatter.ofPattern(pattern,Locale.CHINA).format(time1);
json = JSON.toJSONStringWithDateFormat(test,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteDateUseDateFormat);
Assert.assertEquals("{\"time1\":\""+stime1+"\",json);
//JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT = default_format;
}
项目:esup-ecandidat
文件:MethodUtils.java
项目:xm-ms-entity
文件:MappingUtils.java
public static String format(Instant instant,String pattern) {
if (instant != null) {
try {
return DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.systemDefault()).format(instant);
} catch (DateTimeException | IllegalArgumentException e) {
log.error("Wrong instant: {} or pattern: {}",instant,pattern,e);
return null;
}
}
return null;
}
项目:openjdk-jdk10
文件:TCKDateTimeFormatter.java
@Test
public void test_resolverFields_listofOneNull() throws Exception {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(YEAR).toFormatter().withResolverFields((TemporalField) null);
TemporalAccessor parsed = f.parse("2012");
assertEquals(parsed.isSupported(YEAR),false); // not in the list of resolverFields
}
项目:jdk8u-jdk
文件:TCKDateTimeFormatter.java
@Test
public void test_toFormat_parSEObject_StringParsePosition() throws Exception {
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
ParsePosition pos = new ParsePosition(0);
TemporalAccessor result = (TemporalAccessor) format.parSEObject("ONE30XXX",pos);
assertEquals(pos.getIndex(),5);
assertEquals(pos.getErrorIndex(),-1);
assertEquals(result.isSupported(DAY_OF_MONTH),true);
assertEquals(result.getLong(DAY_OF_MONTH),30L);
}
项目:tipi-engine
文件:Activity.java
protected LocalDate getLocalDateVariable(String name) {
Integer i = (Integer) facade.getvariable(name);
if (i != null) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
formatter = formatter.withLocale(Locale.french);
LocalDate date = LocalDate.parse("" + i,formatter);
return date;
}
return null;
}
项目:qpp-conversion-tool
文件:JsonWrapper.java
/**
* Validates that the given value conforms to expected date formatting (i.e. yyyyMMdd).
*
* @param value to validate
* @return valid date String
* @throws EncodeException
*/
protected String validDate(String value) {
try {
LocalDate thisDate = LocalDate.parse(cleanString(value),DateTimeFormatter.ofPattern("yyyyMMdd"));
return thisDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} catch (Exception e) {
throw new EncodeException(value + " is not an date of format YYYYMMDD.",e);
}
}
项目:jdk8u-jdk
文件:TCKDateTimeFormatter.java
@Test
public void test_resolverFields_ignoreCrossCheck() throws Exception {
DateTimeFormatter base = new DateTimeFormatterBuilder()
.appendValue(YEAR).appendLiteral('-').appendValue(DAY_OF_YEAR).appendLiteral('-')
.appendValue(DAY_OF_WEEK).toFormatter();
DateTimeFormatter f = base.withResolverFields(YEAR,DAY_OF_YEAR);
try {
base.parse("2012-321-1",LocalDate::from); // wrong day-of-week
fail();
} catch (DateTimeException ex) {
// expected,should fail in cross-check of day-of-week
}
LocalDate parsed = f.parse("2012-321-1",LocalDate::from); // ignored wrong day-of-week
assertEquals(parsed,LocalDate.of(2012,11,16));
}
项目:openjdk-jdk10
文件:TestDateTimeFormatterBuilder.java
@Test(dataProvider="offsetPatterns")
public void test_appendOffset_parse(String pattern,s);
ZoneOffset parsed = f.parse(expected,ZoneOffset::from);
assertEquals(f.format(parsed),expected);
}
项目:JSK
文件:JSKDateConverter.java
/**
* This method returns as {@link String} the {@link LocalDateTime} passed as parameter using a {@link DateTimeFormatter}.
* @param date {@link LocalDateTime}
* @param formatter {@link DateTimeFormatter}
* @return {@link String}
* @throws JSKException if some of the parameters are null.
*/
public static String datetoString(LocalDateTime date,DateTimeFormatter formatter) throws JSKException {
if (isNull(date,formatter)) {
throw new JSKException(NULL_ParaMETERS);
}
return date.format(formatter);
}
项目:jdk8u-jdk
文件:TCKDateTimeFormatter.java
@Test
public void test_toFormat_parSEObject_String() throws Exception {
DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
Format format = test.toFormat();
TemporalAccessor result = (TemporalAccessor) format.parSEObject("ONE30");
assertEquals(result.isSupported(DAY_OF_MONTH),30L);
}
/**Method that allows other methods to find a particular show
* @param eventName The name of the event that is being looked for
* @param showStart The date and time of the start of the show
* in the dd.MM.yyyy HH:mm format
* @return A reference to the show object that is being worked on
*/
public Show findShow(String eventName,String showStart)
{
if(findEvent(eventName) != null)
{
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
LocalDateTime startDate = LocalDateTime.parse(showStart,format);
Show show = findEvent(eventName).getShow(startDate);
return show;
}
else
{
return null;
}
}
项目:jdk8u-jdk
文件:TestDateTimeFormatterBuilder.java
@Test
public void test_appendValueReduced_subsequent_parse() throws Exception {
builder.appendValue(MONTH_OF_YEAR,2,SignStyle.norMAL).appendValueReduced(YEAR,2000);
DateTimeFormatter f = builder.toFormatter();
assertEquals(f.toString(),"Value(MonthOfYear,norMAL)ReducedValue(Year,2000)");
ParsePosition ppos = new ParsePosition(0);
TemporalAccessor parsed = f.parseUnresolved("123",ppos);
assertNotNull(parsed,"Parse Failed: " + ppos.toString());
assertEquals(parsed.getLong(MONTH_OF_YEAR),1L);
assertEquals(parsed.getLong(YEAR),2023L);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。