Example usage for org.joda.time DateTime toString

List of usage examples for org.joda.time DateTime toString

Introduction

In this page you can find the example usage for org.joda.time DateTime toString.

Prototype

public String toString(String pattern) 

Source Link

Document

Output the instant using the specified format pattern.

Usage

From source file:com.chiorichan.plugin.lua.api.OSAPI.java

License:Mozilla Public License

@Override
void initialize() {
    // Push a couple of functions that override original Lua API functions or
    // that add new functionality to it.
    lua.getGlobal("os");

    // Custom os.clock() implementation returning the time the computer has
    // been actively running, instead of the native library...
    lua.pushJavaFunction(new JavaFunction() {
        @Override//  w w w.  jav a 2 s . c o  m
        public int invoke(LuaState lua) {
            lua.pushNumber(System.currentTimeMillis());
            return 1;
        }
    });
    lua.setField(-2, "clock");

    lua.pushJavaFunction(new JavaFunction() {
        @Override
        public int invoke(LuaState lua) {
            String format = lua.getTop() > 0 && lua.isString(1) ? lua.toString(1) : "%d/%m/%y %H:%M:%S";
            long time = (long) (lua.getTop() > 1 && lua.isNumber(2) ? lua.toNumber(2) * 1000 / 60 / 60
                    : System.currentTimeMillis());
            DateTime dt = new DateTime(time);
            if (format == "*t") {
                lua.newTable(0, 8);
                lua.pushInteger(dt.year().get());
                lua.setField(-2, "year");
                lua.pushInteger(dt.monthOfYear().get());
                lua.setField(-2, "month");
                lua.pushInteger(dt.dayOfMonth().get());
                lua.setField(-2, "day");
                lua.pushInteger(dt.hourOfDay().get());
                lua.setField(-2, "hour");
                lua.pushInteger(dt.minuteOfHour().get());
                lua.setField(-2, "min");
                lua.pushInteger(dt.secondOfMinute().get());
                lua.setField(-2, "sec");
                lua.pushInteger(dt.dayOfWeek().get());
                lua.setField(-2, "wday");
                lua.pushInteger(dt.dayOfYear().get());
                lua.setField(-2, "yday");
            } else
                lua.pushString(dt.toString(DateTimeFormat.forPattern(format)));
            return 1;
        }
    });
    lua.setField(-2, "date");

    /*
     * // Date formatting function.
     * lua.pushScalaFunction(lua => {
     * val format =
     * if (lua.getTop > 0 && lua.isString(1)) lua.toString(1)
     * else "%d/%m/%y %H:%M:%S"
     * val time =
     * if (lua.getTop > 1 && lua.isNumber(2)) lua.toNumber(2) * 1000 / 60 / 60
     * else machine.worldTime + 5000
     * 
     * val dt = GameTimeFormatter.parse(time)
     * def fmt(format: String) {
     * if (format == "*t") {
     * lua.newTable(0, 8)
     * lua.pushInteger(dt.year)
     * lua.setField(-2, "year")
     * lua.pushInteger(dt.month)
     * lua.setField(-2, "month")
     * lua.pushInteger(dt.day)
     * lua.setField(-2, "day")
     * lua.pushInteger(dt.hour)
     * lua.setField(-2, "hour")
     * lua.pushInteger(dt.minute)
     * lua.setField(-2, "min")
     * lua.pushInteger(dt.second)
     * lua.setField(-2, "sec")
     * lua.pushInteger(dt.weekDay)
     * lua.setField(-2, "wday")
     * lua.pushInteger(dt.yearDay)
     * lua.setField(-2, "yday")
     * }
     * else {
     * lua.pushString(GameTimeFormatter.format(format, dt))
     * }
     * }
     * 
     * // Just ignore the allowed leading '!', Minecraft has no time zones...
     * if (format.startsWith("!"))
     * fmt(format.substring(1))
     * else
     * fmt(format)
     * 1
     * })
     * lua.setField(-2, "date")
     * 
     * // Return ingame time for os.time().
     * lua.pushScalaFunction(lua => {
     * if (lua.isNoneOrNil(1)) {
     * // Game time is in ticks, so that each day has 24000 ticks, meaning
     * // one hour is game time divided by one thousand. Also, Minecraft
     * // starts days at 6 o'clock, versus the 1 o'clock of timestamps so we
     * // add those five hours. Thus:
     * // timestamp = (time + 5000) * 60[kh] * 60[km] / 1000[s]
     * lua.pushNumber((machine.worldTime + 5000) * 60 * 60 / 1000)
     * }
     * else {
     * def getField(key: String, d: Int) = {
     * lua.getField(-1, key)
     * val res = lua.toIntegerX(-1)
     * lua.pop(1)
     * if (res == null)
     * if (d < 0) throw new Exception("field '" + key + "' missing in date table")
     * else d
     * else res: Int
     * }
     * 
     * lua.checkType(1, LuaType.TABLE)
     * lua.setTop(1)
     * 
     * val sec = getField("sec", 0)
     * val min = getField("min", 0)
     * val hour = getField("hour", 12)
     * val mday = getField("day", -1)
     * val mon = getField("month", -1)
     * val year = getField("year", -1)
     * 
     * GameTimeFormatter.mktime(year, mon, mday, hour, min, sec) match {
     * case Some(time) => lua.pushNumber(time)
     * case _ => lua.pushNil()
     * }
     * }
     * 1
     * })
     * lua.setField(-2, "time")
     */
    // Pop the os table.
    lua.pop(1);
}

From source file:com.collective.celos.Util.java

License:Apache License

public static String toNominalTimeFormat(DateTime dt) {
    return dt.toString(DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm'Z"));
}

From source file:com.dianping.data.warehouse.canaan.parser.OptionParser.java

License:Open Source License

/**
 * @param args//from   w  w  w.  ja  v a2s  . c o m
 * @param map
 * @return
 * @throws Exception
 */
public static void process(String[] args, Map<String, String> map) throws Exception {

    CommandLine cl = parser.parse(options, args);

    /*
       * for no args case
     */
    if (cl.getOptions().length > 0) {
        if (cl.hasOption(Constants.PARAM_IN_H)) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("Options", options);
            throw new CanaanPrintHelpException("Print Help");
        } else {
            /*
             * for dol str
             */
            if (cl.hasOption(Constants.PARAM_IN_STR) && cl.hasOption(Constants.PARAM_IN_DOL))
                throw new ParamNotSupportException("ARGS_CONFILCTED");
            if (cl.hasOption(Constants.PARAM_IN_T) && (cl.hasOption(Constants.PARAM_IN_D)))
                throw new ParamNotSupportException("ARGS_CONFILCTED");
            else if (cl.hasOption(Constants.PARAM_IN_STR))
                map.put(Constants.BATCH_COMMON_VARS.BATCH_DOL_TYPE.toString(), Constants.DOL_TYPE_STR);
            else
                map.put(Constants.BATCH_COMMON_VARS.BATCH_DOL_TYPE.toString(), Constants.DOL_TYPE_DOL);

            /*
                 * load common args
             */
            for (String key : Constants.param2ContextVarMapping.keySet()) {
                String value = cl.getOptionValue(key);

                String var = Constants.param2ContextVarMapping.get(key);
                /*
                 * date to standard date string
                */
                if (var.equals(Constants.BATCH_COMMON_VARS.BATCH_CAL_DT.toString())) {
                    if (value != null) {
                        try {
                            value = DateUtils.getFormatDateString(value);
                        } catch (Exception e) {
                            throw new ParamNotSupportException("ERROR_DATE_VALUE_NOTSUPPORT");
                        }
                    }
                } else if (var.equals(Constants.BATCH_COMMON_VARS.BATCH_TIMESTAMP.toString())) {
                    if (value != null) {
                        try {
                            long ts = Long.parseLong(value);
                            long min_ts = Long.parseLong("1000000000000");
                            if (ts <= min_ts) {
                                ts *= 1000;
                            }
                            ts -= 3600000;
                            DateTime d = new DateTime(ts);
                            map.put(Constants.BATCH_COMMON_VARS.BATCH_CAL_DT.toString(),
                                    DateUtils.getFormatDateString(d.toString("yyyy-MM-dd")));
                            value = d.toString("HH");
                        } catch (Exception e) {
                            throw new ParamNotSupportException("ERROR_DATE_VALUE_NOTSUPPORT");
                        }
                    }
                }
                /*
                 * dol pathname => filename
                */
                else if (var.equals(Constants.BATCH_COMMON_VARS.BATCH_DOL.toString())) {
                    if (value != null) {
                        try {
                            value = value.substring(value.lastIndexOf(File.separator) + 1);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            throw new ParamNotSupportException("ERROR_DOL_FILENAME");
                        }
                    }
                }
                // System.out.println("-" + key + ": " + val);
                map.put(Constants.param2ContextVarMapping.get(key), value);

            }
            /*
             * parse only option for -print
            */
            if (cl.hasOption(Constants.PARAM_IN_PRINT)) {
                map.put(Constants.param2ContextVarMapping.get(Constants.PARAM_IN_PRINT), "T");
            } else {
                map.put(Constants.param2ContextVarMapping.get(Constants.PARAM_IN_PRINT), "F");
            }

            /*
                 * load extended args
             */
            Properties keys = cl.getOptionProperties(Constants.PARAM_IN_EXT);
            for (Object key : keys.keySet()) {
                map.put(key.toString(), keys.getProperty(key.toString()));
                // System.out.println("-" + Constants.PARAM_IN_EXT + " " +
                // key + "="
                // + keys.getProperty(key.toString()));
            }

        }
    } else {
        throw new ParamNotSupportException("ERROR_NOARGS");
    }

}

From source file:com.dtstack.jlogstash.render.Formatter.java

License:Apache License

public static String format(Map event, String format, String Timezone) {
    Matcher m = p.matcher(format);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String match = m.group();
        String key = (String) match.subSequence(2, match.length() - 1);
        if (key.equalsIgnoreCase("+s")) {
            Object o = event.get("@timestamp");
            if (o.getClass() == Long.class) {
                m.appendReplacement(sb, o.toString());
            }//  w w  w. j  a  v a2  s. c om
        } else if (key.startsWith("+")) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern((String) key.subSequence(1, key.length()))
                    .withZone(DateTimeZone.forID(Timezone));
            Object o = event.get("@timestamp");
            if (o == null) {
                DateTime timestamp = new DateTime();
                m.appendReplacement(sb, timestamp.toString(formatter));
            } else {
                if (o.getClass() == DateTime.class) {
                    m.appendReplacement(sb, ((DateTime) o).toString(formatter));
                } else if (o.getClass() == Long.class) {
                    DateTime timestamp = new DateTime((Long) o);
                    m.appendReplacement(sb, timestamp.toString(formatter));
                } else if (o.getClass() == String.class) {
                    DateTime timestamp = ISOformatter.parseDateTime((String) o);
                    m.appendReplacement(sb, timestamp.toString(formatter));
                }
            }
        } else if (event.containsKey(key)) {
            m.appendReplacement(sb, event.get(key).toString());
        }

    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.ecofactor.qa.automation.util.DateUtil.java

License:Open Source License

/**
 * Gets the uTC date./*w ww  .j  a  v  a2  s . c om*/
 * @return the uTC date
 */
public static Date getUTCDate() {

    DateTime dt = new DateTime(DateTimeZone.UTC);
    Date utcDate = null;
    try {
        utcDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dt.toString("yyyy-MM-dd HH:mm:ss"));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    LOGGER.debug("Current UTC Date " + formatToUTC(utcDate, DATE_FMT_FULL_TZ));
    return utcDate;
}

From source file:com.egt.core.util.STP.java

License:Open Source License

public static String getString(Object obj) {
    if (obj == null) {
        return null;
    } else if (obj instanceof String) {
        return obj.toString();
    } else if (obj instanceof Integer) {
        return obj.toString();
    } else if (obj instanceof Long) {
        return obj.toString();
    } else if (obj instanceof BigInteger) {
        return obj.toString();
    } else if (obj instanceof BigDecimal) {
        /*//from   www  . j a v  a  2  s. c o  m
         * OJO: configuracion regional (signo, punto y coma)
         */
        return obj.toString();
    } else if (obj instanceof Boolean) {
        return obj.toString();
    } else if (obj instanceof Date) {
        /*
         * OJO: configuracion regional
         */
        return new DateTime(obj).toString("dd/MM/yyyy");
    } else if (obj instanceof Time) {
        /*
         * OJO: configuracion regional
         */
        return new DateTime(obj).toString("hh:mm aa");
    } else if (obj instanceof Timestamp || obj instanceof java.util.Date) {
        /*
         * OJO: configuracion regional
         */
        DateTime datetime = new DateTime(obj);
        String pattern = datetime.getMillisOfDay() == 0 ? "dd/MM/yyyy" : "dd/MM/yyyy hh:mm:ss aa";
        return datetime.toString(pattern);
    } else {
        return obj.toString();
    }
}

From source file:com.egt.web.configuracion.basica.FragmentoPie2.java

License:Open Source License

public String getTimestampString() {
    Date date = new Date();
    DateTime fecha = new DateTime(date);
    return fecha.toString("dd/MM/yyyy hh:mm:ss");
}

From source file:com.epam.ta.reportportal.core.widget.content.StatisticBasedContentLoader.java

License:Open Source License

/**
 * Create ranged empty timeline billet/* w  w w .j av a 2 s  .  c  o  m*/
 * 
 * @param base
 * @param period
 * @return
 */
private Map<String, ChartObject> buildRange(List<ChartObject> base, Period period) {
    final LongSummaryStatistics statistics = base.stream()
            .mapToLong(object -> Long.valueOf(object.getStartTime())).summaryStatistics();
    final DateTime start = new DateTime(statistics.getMin());
    final DateTime end = new DateTime(statistics.getMax());
    DateTime intermediate = start;
    final LinkedHashMap<String, ChartObject> map = new LinkedHashMap<>();
    if (base.isEmpty())
        return map;
    while (intermediate.isBefore(end)) {
        map.put(intermediate.toString(DATE_PATTERN), createChartObject(base.get(0)));
        switch (period) {
        case DAY:
            intermediate = intermediate.plusDays(1);
            break;
        case WEEK:
            intermediate = intermediate.plusDays(1);
            break;
        case MONTH:
            intermediate = intermediate.plusMonths(1);
            break;
        }
    }
    map.put(end.toString(DATE_PATTERN), createChartObject(base.get(0)));
    return map;
}

From source file:com.example.getstarted.util.CloudStorageHelper.java

License:Apache License

/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 *//* w  w  w.  j  a va  2 s.  co m*/
public String uploadFile(FileItemStream fileStream, final String bucketName)
        throws IOException, ServletException {
    checkFileExtension(fileStream.getName());

    DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
    DateTime dt = DateTime.now(DateTimeZone.UTC);
    String dtString = dt.toString(dtf);
    final String fileName = fileStream.getName() + dtString;

    // the inputstream is closed by default, so we don't need to close it here
    BlobInfo blobInfo = storage.create(BlobInfo.newBuilder(bucketName, fileName)
            // Modify access list to allow all users with link to read file
            .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))).build(),
            fileStream.openStream());
    logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[] { fileStream.getName(), fileName });
    // return the public download link
    return blobInfo.getMediaLink();
}

From source file:com.example.getstarted.util.DatastoreSessionFilter.java

License:Apache License

/**
 * Stores the state value in each key-value pair in the project's datastore.
 * @param sessionId Request from which to extract session.
 * @param varName the name of the desired session variable
 * @param varValue the value of the desired session variable
 *///from   w w  w . j  a  va  2s.  co m
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
    if (sessionId.equals("")) {
        return;
    }
    Key key = KeyFactory.createKey(SESSION_KIND, sessionId);
    Transaction transaction = datastore.beginTransaction();
    DateTime dt = DateTime.now(DateTimeZone.UTC);
    dt.toString(DTF);
    try {
        Entity stateEntity;
        try {
            stateEntity = datastore.get(transaction, key);
        } catch (EntityNotFoundException e) {
            stateEntity = new Entity(key);
        }
        for (String varName : setMap.keySet()) {
            stateEntity.setProperty(varName, setMap.get(varName));
        }
        stateEntity.setProperty("lastModified", dt.toString(DTF));
        datastore.put(transaction, stateEntity);
        transaction.commit();
    } finally {
        if (transaction.isActive()) {
            transaction.rollback();
        }
    }
}