List of usage examples for org.joda.time.format DateTimeFormatter print
public String print(ReadablePartial partial)
From source file:io.prestosql.operator.scalar.DateTimeFunctions.java
License:Apache License
@ScalarFunction("to_iso8601") @SqlType("varchar(35)") // YYYY-MM-DDTHH:MM:SS.mmm+HH:MM is a standard notation, and it requires 29 characters. // However extended notation with format (Y)+-MM-DDTHH:MM:SS.mmm+HH:MM is also acceptable and as // the maximum year represented by 64bits timestamp is ~584944387 it may require up to 35 characters. public static Slice toISO8601FromTimestampWithTimeZone( @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long timestampWithTimeZone) { long millisUtc = unpackMillisUtc(timestampWithTimeZone); DateTimeFormatter formatter = ISODateTimeFormat.dateTime() .withChronology(getChronology(unpackZoneKey(timestampWithTimeZone))); return utf8Slice(formatter.print(millisUtc)); }
From source file:io.prestosql.operator.scalar.DateTimeFunctions.java
License:Apache License
@ScalarFunction("to_iso8601") @SqlType("varchar(16)") // Standard format is YYYY-MM-DD, which gives up to 10 characters. // However extended notation with format (Y)+-MM-DD is also acceptable and as the maximum year // represented by 64bits timestamp is ~584944387 it may require up to 16 characters to represent a date. public static Slice toISO8601FromDate(ConnectorSession session, @SqlType(StandardTypes.DATE) long date) { DateTimeFormatter formatter = ISODateTimeFormat.date().withChronology(UTC_CHRONOLOGY); return utf8Slice(formatter.print(DAYS.toMillis(date))); }
From source file:io.prestosql.operator.scalar.DateTimeFunctions.java
License:Apache License
private static Slice dateFormat(ISOChronology chronology, Locale locale, long timestamp, Slice formatString) { DateTimeFormatter formatter = DATETIME_FORMATTER_CACHE.get(formatString).withChronology(chronology) .withLocale(locale);/*from w w w.j av a 2s. c o m*/ return utf8Slice(formatter.print(timestamp)); }
From source file:io.prestosql.plugin.hive.HivePartitionManager.java
License:Apache License
private List<String> getFilteredPartitionNames(SemiTransactionalHiveMetastore metastore, SchemaTableName tableName, List<HiveColumnHandle> partitionKeys, TupleDomain<ColumnHandle> effectivePredicate) { checkArgument(effectivePredicate.getDomains().isPresent()); List<String> filter = new ArrayList<>(); for (HiveColumnHandle partitionKey : partitionKeys) { Domain domain = effectivePredicate.getDomains().get().get(partitionKey); if (domain != null && domain.isNullableSingleValue()) { Object value = domain.getNullableSingleValue(); Type type = domain.getType(); if (value == null) { filter.add(HivePartitionKey.HIVE_DEFAULT_DYNAMIC_PARTITION); } else if (type instanceof CharType) { Slice slice = (Slice) value; filter.add(padSpaces(slice, type).toStringUtf8()); } else if (type instanceof VarcharType) { Slice slice = (Slice) value; filter.add(slice.toStringUtf8()); }/*from ww w .j a v a 2s . co m*/ // Types above this have only a single possible representation for each value. // Types below this may have multiple representations for a single value. For // example, a boolean column may represent the false value as "0", "false" or "False". // The metastore distinguishes between these representations, so we cannot prune partitions // unless we know that all partition values use the canonical Java representation. else if (!assumeCanonicalPartitionKeys) { filter.add(PARTITION_VALUE_WILDCARD); } else if (type instanceof DecimalType && !((DecimalType) type).isShort()) { Slice slice = (Slice) value; filter.add(Decimals.toString(slice, ((DecimalType) type).getScale())); } else if (type instanceof DecimalType && ((DecimalType) type).isShort()) { filter.add(Decimals.toString((long) value, ((DecimalType) type).getScale())); } else if (type instanceof DateType) { DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.date().withZoneUTC(); filter.add(dateTimeFormatter.print(TimeUnit.DAYS.toMillis((long) value))); } else if (type instanceof TimestampType) { // we don't have time zone info, so just add a wildcard filter.add(PARTITION_VALUE_WILDCARD); } else if (type instanceof TinyintType || type instanceof SmallintType || type instanceof IntegerType || type instanceof BigintType || type instanceof DoubleType || type instanceof RealType || type instanceof BooleanType) { filter.add(value.toString()); } else { throw new PrestoException(NOT_SUPPORTED, format("Unsupported partition key type: %s", type.getDisplayName())); } } else { filter.add(PARTITION_VALUE_WILDCARD); } } // fetch the partition names return metastore.getPartitionNamesByParts(tableName.getSchemaName(), tableName.getTableName(), filter) .orElseThrow(() -> new TableNotFoundException(tableName)); }
From source file:io.spikex.core.helper.Variables.java
License:Apache License
private Object resolveValue(final JsonObject event, final String var) { Object value = null;/* w w w . j a va 2 s . c om*/ if (var.length() > 0) { if (var.startsWith(BUILTIN_PREFIX)) { DateTime dtNow; DateTimeFormatter fmt; if (var.startsWith(BUILTIN_SDF)) { // Simple date format String pattern = var.substring(BUILTIN_SDF.length()); dtNow = new DateTime(DateTimeZone.UTC); fmt = DateTimeFormat.forPattern(pattern); value = fmt.print(dtNow); } else if (var.startsWith(BUILTIN_ENV)) { // env Object val = m_systemEnv.get(var.substring(BUILTIN_ENV.length())); value = (val != null ? String.valueOf(val) : ""); } else if (var.startsWith(BUILTIN_PROP)) { // prop Object val = m_systemProps.get(var.substring(BUILTIN_PROP.length())); value = (val != null ? String.valueOf(val) : ""); } else if (var.startsWith(BUILTIN_METRIC)) { // metrics if (m_vertx != null) { Map<String, Object> values = m_vertx.sharedData().getMap(SHARED_METRICS_KEY); value = values.get(var.substring(BUILTIN_METRIC.length())); } } else if (var.startsWith(BUILTIN_SENSOR)) { // sensor if (m_vertx != null) { Map<String, Object> values = m_vertx.sharedData().getMap(SHARED_SENSORS_KEY); value = values.get(var.substring(BUILTIN_SENSOR.length())); } } else if (var.startsWith(BUILTIN_NOW_EXTENDED)) { // now extended with timezone and time offset DateTime dt = Variables.createDateTimeNow(var); value = dt.getMillis(); } else { switch (var) { case BUILTIN_NODE: value = m_nodeName; break; case BUILTIN_CLUSTER: value = m_clusterName; break; case BUILTIN_SPIKEX_HOME: value = m_spikexHome; break; case BUILTIN_SPIKEX_CONF: value = m_spikexConf; break; case BUILTIN_SPIKEX_DATA: value = m_spikexData; break; case BUILTIN_SPIKEX_TMP: value = m_spikexTmp; break; case BUILTIN_CHAIN: value = m_chainName; break; case BUILTIN_HOST: value = m_hostName; break; case BUILTIN_DATE: dtNow = new DateTime(DateTimeZone.UTC); fmt = ISODateTimeFormat.basicDate(); value = fmt.print(dtNow); break; case BUILTIN_TIMESTAMP: dtNow = new DateTime(DateTimeZone.UTC); fmt = ISODateTimeFormat.basicDateTime(); value = fmt.print(dtNow); break; case BUILTIN_NOW: value = System.currentTimeMillis(); break; default: value = var; // Just return the variable def break; } } } else { // // Retrieve value from existing field in the event // if (event != null) { value = event.getValue(var); } } } return value; }
From source file:io.squarely.vertxspike.collectors.CollectorVerticle.java
License:Apache License
private String getISODateString(DateTime dt, DateTimeFormatter dateTimeFormatter) { return dateTimeFormatter.print(dt); }
From source file:io.verticle.oss.apex.service.processing.inbound.IndexCompatibleDateTimeFormatter.java
License:Apache License
public static String getIsoFormattedDateString(Date date) { String formatted = null;/*from ww w . ja va 2 s . c o m*/ if (date != null) { DateTime dt = new DateTime(date); DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); formatted = fmt.print(dt); } return formatted; }
From source file:io.warp10.script.functions.ISO8601.java
License:Apache License
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object obj = stack.peek();//from ww w . j a v a 2 s . com String tz = null; if (obj instanceof String) { tz = (String) obj; stack.pop(); } else if (!(obj instanceof Long)) { throw new WarpScriptException(getName() + " operates on a timestamp or a timestamp + timezone."); } obj = stack.pop(); if (!(obj instanceof Long)) { throw new WarpScriptException(getName() + " operates on a timestamp or a timestamp + timezone."); } long ts = (long) obj; DateTimeFormatter dtf; // // Set the timezone // if (null == tz) { dtf = this.dtf.withZoneUTC(); } else { dtf = this.dtf.withZone(DateTimeZone.forID(tz)); } long millis = ts / Constants.TIME_UNITS_PER_MS; String dt = dtf.print(millis); if (Constants.TIME_UNITS_PER_MS > 1) { // // Add sub millisecond string // StringBuilder sb = new StringBuilder(); sb.append(dt, 0, 23); long subms = Constants.TIME_UNITS_PER_MS; subms += ts % Constants.TIME_UNITS_PER_MS; String str = Long.toString(subms); sb.append(str, 1, str.length()); sb.append(dt, 23, dt.length()); stack.push(sb.toString()); } else { stack.push(dt); } return stack; }
From source file:it.webappcommon.lib.DateUtils.java
License:Open Source License
/** * http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ * DateTimeFormat.html//from w w w . j a v a 2 s .c om * * @param aDate * @return */ public static String getWeekOfTheYearKey(Date aDate) { DateTime dateTime = new DateTime(aDate); DateTimeFormatter fmt = DateTimeFormat.forPattern("x-'W'w"); return fmt.print(dateTime); }
From source file:jongo.demo.Demo.java
License:Open Source License
private static void generateDemoDatabase(final DatabaseConfiguration dbcfg) { final String database = dbcfg.getDatabase(); QueryRunner run = new QueryRunner(JDBCConnectionFactory.getDataSource(dbcfg)); l.info("Generating Demo resources in database {}", database); update(run, getCreateAuthTable());//from www. ja v a2 s. c o m update(run, getCreateUserTable()); update(run, getCreateMakersTable()); update(run, getCreateCarsTable()); update(run, getCreateCommentsTable()); update(run, getCreatePicturesTable()); update(run, getCreateSalesStatsTable()); update(run, getCreateSalesByMakerAndModelStatsTable()); update(run, getCreateEmptyTable()); l.info("Generating Demo Data in database {}", database); final String insertAuthQuery = "INSERT INTO jongo_auth (email, password) VALUES (?,?)"; update(run, insertAuthQuery, "a@a.com", JongoUtils.getHashedPassword("123456")); update(run, insertAuthQuery, "a@b.com", JongoUtils.getHashedPassword("This is a test")); final String insertUserQuery = "INSERT INTO users (name, age, birthday, credit) VALUES (?,?,?,?)"; update(run, insertUserQuery, "foo", 30, "1982-12-13", 32.5); update(run, insertUserQuery, "bar", 33, "1992-01-15", 0); for (CarMaker maker : CarMaker.values()) { update(run, "INSERT INTO maker (name, realname) VALUES (?,?)", maker.name(), maker.getRealName()); } final String insertCar = "INSERT INTO car (maker, model, year, fuel, transmission, currentMarketValue, newValue) VALUES (?,?,?,?,?,?,?)"; update(run, insertCar, "CITROEN", "C2", 2008, "Gasoline", "Manual", 9000, 13000); update(run, "INSERT INTO car (maker, model, year, transmission, currentMarketValue, newValue) VALUES (?,?,?,?,?,?)", "FIAT", "500", 2010, "Manual", 19000, 23.000); update(run, insertCar, "BMW", "X5", 2011, "Diesel", "Automatic", 59000, 77000); final String insertComment = "INSERT INTO comments (car_id, car_comment) VALUES (?,?)"; update(run, insertComment, 0, "The Citroen C2 is a small car with a great attitude"); update(run, insertComment, 0, "I Love my C2"); update(run, insertComment, 2, "BMW's X5 costs too much for what it's worth. Checkout http://www.youtube.com/watch?v=Bg1TB4dRobY"); final String insertPicture = "INSERT INTO pictures (car_id, picture) VALUES (?,?)"; update(run, insertPicture, 0, "http://www.babez.de/citroen/c2/picth01.jpg"); update(run, insertPicture, 0, "http://www.babez.de/citroen/c2/pic02.jpg"); update(run, insertPicture, 0, "http://www.babez.de/citroen/c2/picth03.jpg"); update(run, insertPicture, 1, "http://www.dwsauto.com/wp-content/uploads/2008/07/fiat-500-photo.jpg"); update(run, insertPicture, 1, "http://www.cochesadictos.com/coches/fiat-500/imagenes/index1.jpg"); update(run, insertPicture, 1, "http://www.cochesadictos.com/coches/fiat-500/imagenes/index4.jpg"); update(run, insertPicture, 2, "http://www.coches21.com/fotos/100/bmw_x5_457.jpg"); update(run, insertPicture, 2, "http://www.coches21.com/fotos/100/bmw_x5_460.jpg"); update(run, insertPicture, 2, "http://www.coches21.com/modelos/250/bmw_x5_65.jpg"); // generate some random data for the stats page DateTimeFormatter isofmt = ISODateTimeFormat.dateTime(); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS"); DateTime dt;// = isofmt.parseDateTime("2012-01-16T13:34:00.000Z"); for (int year = 2000; year < 2012; year++) { for (int month = 1; month <= 12; month++) { int val = 1910 + new Random().nextInt(100); dt = isofmt.parseDateTime(year + "-" + month + "-01T01:00:00.000Z"); update(run, "INSERT INTO sales_stats (year, month, sales, last_update) VALUES (?,?,?,?)", year, month, val, fmt.print(dt)); for (CarMaker maker : CarMaker.values()) { val = new Random().nextInt(100); update(run, "INSERT INTO maker_stats (year, month, sales, maker, last_update) VALUES (?,?,?,?,?)", year, month, val, maker.name(), fmt.print(dt)); } } } update(run, "SET TABLE maker READONLY TRUE"); //load the sp update(run, "CREATE FUNCTION simpleStoredProcedure () RETURNS TINYINT RETURN 1"); update(run, "CREATE PROCEDURE insert_comment (IN car_id INTEGER, IN car_comment VARCHAR(255)) MODIFIES SQL DATA INSERT INTO comments VALUES (DEFAULT, car_id, car_comment)"); update(run, "CREATE PROCEDURE get_year_sales (IN in_year INTEGER, OUT out_total INTEGER) READS SQL DATA SELECT COUNT(sales) INTO out_total FROM sales_stats WHERE year = in_year"); update(run, getCreateView()); }