Java Code Examples for java.time.LocalDateTime#format()

The following examples show how to use java.time.LocalDateTime#format() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GreeterImpl.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloRequest.DateTime reqDateTime = req.getDateTime();
    int i = 0;
    try {
        i = Integer.parseInt(reqDateTime.getTime());
    } catch (Exception e) {
        //TODO: handle exception
    }
    LocalDateTime dt = LocalDateTime.now();
    String dtStr = dt.format(datetimeFormatter[i % datetimeFormatter.length]);
    HelloRequest.DateTime rplyDateTime = HelloRequest.DateTime.newBuilder(reqDateTime)
        .setDate(dtStr).build();
    HelloReply reply = HelloReply.newBuilder()
        .setMessage("Hello " + req.getName())
        .setDateTime(rplyDateTime)
        .build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
}
 
Example 2
Source File: RollerTimestamp.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Override
public Path nextFilename() {
    for ( int i = 1 ; ; i++ ) {
        // This "must" be unique unless it is the same time as last time
        // because time moves forward and we checked for future files in init().
        LocalDateTime timestamp = LocalDateTime.now();
        String fn = baseFilename + DATETIME_SEP + timestamp.format(fmtDateTime);
        Path path = directory.resolve(fn);
        if ( ! Files.exists(path) ) {
            valid = true;
            lastTimestamp = timestamp;
            lastAllocatedPath = path;
            return lastAllocatedPath;
        }
        // Try again.
        if ( i == RETRIES)
            throw new FileRotateException("Failed to find a new, fresh filename: "+timestamp);
        Lib.sleep(1000);
    }
}
 
Example 3
Source File: RunKB.java    From wings with Apache License 2.0 5 votes vote down vote up
@Override
public int getNumberOfRuns(String pattern, String status, Date started_after) {
   String starttime = null;
   if(started_after != null) {
     LocalDateTime time = started_after.toInstant()
         .atZone(ZoneId.systemDefault()).toLocalDateTime();
     ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(time);
     starttime = time.format(DateTimeFormatter.ISO_DATE_TIME) + offset.getId();
   }
   
   String query = 
       "PREFIX exec: <http://www.wings-workflows.org/ontology/execution.owl#>\n" + 
        "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" +
       "SELECT (COUNT(*) as ?count)\n" + 
       "WHERE { " +
        "?run a exec:Execution .\n" +
        "?run exec:hasExecutionStatus ?status .\n" +
        "?run exec:hasTemplate ?template .\n" +
        "?run exec:hasStartTime ?start .\n" +
        (status != null ? 
            "?run exec:hasExecutionStatus '" + status + "') .\n" : "") +
        (starttime != null ?
            "FILTER(?start > '"+starttime+"'^^xsd:dateTime) .\n" : "") +      
        (pattern != null ? 
            "FILTER REGEX(str(?template), '" + newtplurl + ".*" + pattern + ".*') .\n" : "") +
        "FILTER REGEX(str(?run), '" + newrunurl + "') .\n" +
       "}";

   this.start_read();
   ArrayList<ArrayList<SparqlQuerySolution>> result = unionkb.sparqlQuery(query);
   int size = (Integer) result.get(0).get(0).getObject().getValue();
   this.end();
   return size;
}
 
Example 4
Source File: AcademicFacadeImpl.java    From Java-EE-8-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
private void sendEmail (TestRevisionTO testRevisionTO, LocalDateTime dateTime) {
	Student student = studentDAO.getStudentByEnrollment (testRevisionTO.getEnrollment());
	String enrollment = student.getEnrollment(); //testRevisionTO.getEnrollment()
	String studentName = student.getName();
	String email = student.getEmail();
	Discipline discipline = disciplineDAO.getDisciplineByCode (testRevisionTO.getDisciplineCode());
	String disciplineName = discipline.getName(); 
	String disciplineCode = discipline.getCode(); // testRevisionTO.getDisciplineCode()
	String date  = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
	String time  = dateTime.format(DateTimeFormatter.ofPattern("HH:mm"));
	// sending an email using the above information ...
	System.out.println("sending an email to : " + studentName + " ...");
}
 
Example 5
Source File: StockProductServiceOnlineImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize, ChartHistoMovingAverage histoAverage,
		ChartHistoTimeSpan histoPeriod, Integer intradayWidth, Integer intradayHeight) {
	
	Preconditions.checkNotNull(stock, "stock must not be null!");
	Preconditions.checkNotNull(type, "ChartType must not be null!");
	
	String guid = AuthenticationUtil.getPrincipal().getUsername();
	SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
	if(socialUser == null){
		return;
	}
	String token = socialUser.getAccessToken();
	Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);
	
       if (connection != null) {
		byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
		LocalDateTime dateTime = LocalDateTime.now();
		String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
		String imageName = stock.getId().toLowerCase()+"_"+type.name().toLowerCase()+"_"+formattedDateTime+".png";
    	String pathToYahooPicture = env.getProperty("user.home").concat(env.getProperty("pictures.yahoo.path")).concat(File.separator+imageName);
    	
           try {
               Path newPath = Paths.get(pathToYahooPicture);
               Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
           } catch (IOException e) {
               throw new Error("Storage of " + pathToYahooPicture+ " failed", e);
           }
           
           ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, pathToYahooPicture);
           chartStockRepository.save(chartStock);
       }
}
 
Example 6
Source File: PodcastServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Format: "yyyyMMddHHmmssSSS"
 * @param date
 * @return
 */
private static String getSimpleDateFormat(Date date) {
	DateTimeFormatter sss = new DateTimeFormatterBuilder()
			.appendPattern("yyyyMMddHHmmssSSS")
			.toFormatter(resbud.getLocale());
	LocalDateTime userDate1 = LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC);
	return userDate1.format(sss);
}
 
Example 7
Source File: LocalDateTime1.java    From java8-tutorial with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);

        DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
        System.out.println(dayOfWeek);      // WEDNESDAY

        Month month = sylvester.getMonth();
        System.out.println(month);          // DECEMBER

        long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
        System.out.println(minuteOfDay);    // 1439

        Instant instant = sylvester
                .atZone(ZoneId.systemDefault())
                .toInstant();

        Date legacyDate = Date.from(instant);
        System.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014


        DateTimeFormatter formatter =
                DateTimeFormatter
                        .ofPattern("MMM dd, yyyy - HH:mm");

        LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
        String string = parsed.format(formatter);
        System.out.println(string);     // Nov 03, 2014 - 07:13
    }
 
Example 8
Source File: SchedulerTriggerListener.java    From dapeng-soa with Apache License 2.0 5 votes vote down vote up
/**
 * (3) 当Trigger错过被激发时执行,比如当前时间有很多触发器都需要执行,但是线程池中的有效线程都在工作,
 * 那么有的触发器就有可能超时,错过这一轮的触发。
 * Called by the Scheduler when a Trigger has misfired.
 */
@Override
public void triggerMisfired(Trigger trigger) {
    JobDataMap jobDataMap = trigger.getJobDataMap();
    String serviceName = jobDataMap.getString("serviceName");
    String versionName = jobDataMap.getString("versionName");
    String methodName = jobDataMap.getString("methodName");

    LocalDateTime currentTime = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
    trigger.getJobDataMap().put("startTime", currentTime);

    String currentTimeAsString = currentTime.format(DATE_TIME);
    String message = String.format("SchedulerTriggerListener::triggerMisfired;Task[%s:%s:%s] 触发超时,错过[%s]这一轮触发", serviceName, versionName, methodName, currentTimeAsString);
    sendMessage(serviceName, versionName, methodName, executorService, message, true, jobDataMap, "triggerTimeOut");
}
 
Example 9
Source File: GeneralInfoWriter.java    From maestro-java with Apache License 2.0 5 votes vote down vote up
/**
 * Write single record line into csv file
 * @param now current time
 * @param object one line record
 */
@SuppressWarnings("unchecked")
private void write(final LocalDateTime now, final Object object) {
    if (object instanceof Map) {
        final Map<String, Object> routerLinkInfo = (Map<String, Object>) object;

        logger.trace("General information: {}", routerLinkInfo);

        try {
            String timestamp = now.format(formatter);

            csvPrinter.printRecord(timestamp,
                    routerLinkInfo.get("name"), routerLinkInfo.get("version"),
                    routerLinkInfo.get("mode"), routerLinkInfo.get("linkRouteCount"),
                    routerLinkInfo.get("autoLinkCount"), routerLinkInfo.get("linkCount"),
                    routerLinkInfo.get("nodeCount"), routerLinkInfo.get("addrCount"),
                    routerLinkInfo.get("connectionCount"));


        } catch (IOException e) {
            logger.error("Unable to write record: {}", e.getMessage(), e);
        }
    }
    else {
        logger.warn("Invalid value type for general info");
    }
}
 
Example 10
Source File: CookieHttpOnlyScanRuleUnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAlertWhenFutureExpiry() throws HttpMalformedHeaderException {
    // Given - value empty and epoch start date
    HttpMessage msg = new HttpMessage();
    msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
    // When
    msg.setResponseBody("<html></html>");

    DateTimeFormatter df =
            DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz")
                    .withZone(ZoneOffset.UTC);
    LocalDateTime dateTime = LocalDateTime.now().plusYears(1);
    String expiry = dateTime.format(df);

    msg.setResponseHeader(
            "HTTP/1.1 200 OK\r\n"
                    + "Server: Apache-Coyote/1.1\r\n"
                    + "Set-Cookie: test=\"\"; expires="
                    + expiry
                    + "; Path=/; secure\r\n"
                    + "Content-Type: text/html;charset=ISO-8859-1\r\n"
                    + "Content-Length: "
                    + msg.getResponseBody().length()
                    + "\r\n");
    scanHttpResponseReceive(msg);
    // Then
    assertThat(alertsRaised.size(), equalTo(1));
    assertThat(alertsRaised.get(0).getParam(), equalTo("test"));
    assertThat(alertsRaised.get(0).getEvidence(), equalTo("Set-Cookie: test"));
}
 
Example 11
Source File: TimeUtil.java    From game-server with MIT License 5 votes vote down vote up
/**@
 * 获取与今日相差天数的日期格式,负为日期前,正为日期后。如yyyy-MM-dd HH
 *
 * @param days
 * @param formatter
 * @return
 */
public static String getOffToDay(int days, DateTimeFormatter formatter) {
    LocalDateTime ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(currentTimeMillis()), ZoneId.systemDefault());
    if (days < 0) {
        ldt = ldt.minusDays(-days);
    } else {
        ldt = ldt.plusDays(days);
    }
    return ldt.format(formatter);
}
 
Example 12
Source File: StockProductServiceOfflineImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize, ChartHistoMovingAverage histoAverage,
		ChartHistoTimeSpan histoPeriod, Integer intradayWidth, Integer intradayHeight) {
	
	Preconditions.checkNotNull(stock, "stock must not be null!");
	Preconditions.checkNotNull(type, "ChartType must not be null!");
	
	String guid = AuthenticationUtil.getPrincipal().getUsername();
	String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken();
	ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid);
	Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);
	
       if (connection != null) {
		byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
		LocalDateTime dateTime = LocalDateTime.now();
		String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
		String imageName = stock.getId().toLowerCase()+"_"+type.name().toLowerCase()+"_"+formattedDateTime+".png";
    	String pathToYahooPicture = env.getProperty("pictures.yahoo.path").concat(File.separator+imageName);
    	
           try {
               Path newPath = Paths.get(pathToYahooPicture);
               Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
           } catch (IOException e) {
               throw new Error("Storage of " + pathToYahooPicture+ " failed", e);
           }
           
           ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, pathToYahooPicture);
           chartStockRepository.save(chartStock);
       }
}
 
Example 13
Source File: PersonFormatUtil.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the date of birth of the person in the default date format (Ger. dd.MM.yyyy).
 * 
 * @param person
 * @return
 */
public static String getDateOfBirth(IPerson person){
	LocalDateTime dob = person.getDateOfBirth();
	if (dob != null) {
		return dob.format(defaultDateFormatter);
	}
	return "";
}
 
Example 14
Source File: StringFormatUtils.java    From datakernel with Apache License 2.0 4 votes vote down vote up
public static String formatLocalDateTime(LocalDateTime value) {
	value.format(DATE_TIME_FORMATTER);
	return value.toString();
}
 
Example 15
Source File: DateUtil.java    From permission with MIT License 4 votes vote down vote up
public static String formatFullTime(LocalDateTime localDateTime, String pattern) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
    return localDateTime.format(dateTimeFormatter);
}
 
Example 16
Source File: SqlDialect.java    From sqlg with MIT License 4 votes vote down vote up
default String toRDBSStringLiteral(PropertyType propertyType, Object value) {
    switch (propertyType.ordinal()) {
        case BOOLEAN_ORDINAL:
            Boolean b = (Boolean) value;
            return b.toString();
        case BYTE_ORDINAL:
            Byte byteValue = (Byte) value;
            return byteValue.toString();
        case SHORT_ORDINAL:
            Short shortValue = (Short) value;
            return shortValue.toString();
        case INTEGER_ORDINAL:
            Integer intValue = (Integer) value;
            return intValue.toString();
        case LONG_ORDINAL:
            Long longValue = (Long) value;
            return longValue.toString();
        case FLOAT_ORDINAL:
            Float floatValue = (Float) value;
            return floatValue.toString();
        case DOUBLE_ORDINAL:
            Double doubleValue = (Double) value;
            return doubleValue.toString();
        case STRING_ORDINAL:
            return "'" + value.toString() + "'";
        case LOCALDATE_ORDINAL:
            LocalDate localDateValue = (LocalDate) value;
            return "'" + localDateValue.toString() + "'";
        case LOCALDATETIME_ORDINAL:
            LocalDateTime localDateTimeValue = (LocalDateTime) value;
            return "'" + localDateTimeValue.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "'";
        case LOCALTIME_ORDINAL:
            LocalTime localTimeValue = (LocalTime) value;
            return "'" + localTimeValue.toString() + "'";
        case ZONEDDATETIME_ORDINAL:
            break;
        case PERIOD_ORDINAL:
            break;
        case DURATION_ORDINAL:
            break;
        case JSON_ORDINAL:
            break;
        case POINT_ORDINAL:
            break;
        case LINESTRING_ORDINAL:
            break;
        case POLYGON_ORDINAL:
            break;
        case GEOGRAPHY_POINT_ORDINAL:
            break;
        case GEOGRAPHY_POLYGON_ORDINAL:
            break;
        case boolean_ARRAY_ORDINAL:
            break;
        case BOOLEAN_ARRAY_ORDINAL:
            break;
        case byte_ARRAY_ORDINAL:
            break;
        case BYTE_ARRAY_ORDINAL:
            break;
        case short_ARRAY_ORDINAL:
            break;
        case SHORT_ARRAY_ORDINAL:
            break;
        case int_ARRAY_ORDINAL:
            break;
        case INTEGER_ARRAY_ORDINAL:
            break;
        case long_ARRAY_ORDINAL:
            break;
        case LONG_ARRAY_ORDINAL:
            break;
        case float_ARRAY_ORDINAL:
            break;
        case FLOAT_ARRAY_ORDINAL:
            break;
        case double_ARRAY_ORDINAL:
            break;
        case DOUBLE_ARRAY_ORDINAL:
            break;
        case STRING_ARRAY_ORDINAL:
            break;
        case LOCALDATETIME_ARRAY_ORDINAL:
            break;
        case LOCALDATE_ARRAY_ORDINAL:
            break;
        case LOCALTIME_ARRAY_ORDINAL:
            break;
        case ZONEDDATETIME_ARRAY_ORDINAL:
            break;
        case DURATION_ARRAY_ORDINAL:
            break;
        case PERIOD_ARRAY_ORDINAL:
            break;
        case JSON_ARRAY_ORDINAL:
            break;
    }
    return "'" + value.toString() + "'";
}
 
Example 17
Source File: DRDARequest.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
/**
 * Writes a LocalTime to the buffer in the standard SQL format using UTF8 encoding
 */
final void writeTimestamp(LocalDateTime ts) {
  ensureLength(26);
  String t = ts.format(DRDAConstants.DB2_TIMESTAMP_FORMAT);
  buffer.writeCharSequence(t, StandardCharsets.UTF_8);
}
 
Example 18
Source File: ThreadLocalDateUtil.java    From pre with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    String nowStr = now .format(format);
    System.out.println(nowStr);
}
 
Example 19
Source File: TemplateMaker.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public String toString(Object o, String formatString, Locale locale) {
  if (formatString == null) return o.toString();
  LocalDateTime ld = (LocalDateTime) o;
  return ld.format(DateTimeFormatter.ofPattern(formatString));
}
 
Example 20
Source File: TimeUtil.java    From game-server with MIT License 2 votes vote down vote up
/**
 * @
 * @param time
 * @param formatter
 * @return
 */
public static String getDateTimeFormat(long time, DateTimeFormatter formatter) {
    LocalDateTime ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
    return ldt.format(formatter);
}