List of usage examples for java.text SimpleDateFormat setTimeZone
public void setTimeZone(TimeZone zone)
From source file:fr.aliasource.webmail.server.export.ConversationExporter.java
private String formatDate(Date date) { SimpleDateFormat dateFormater = new SimpleDateFormat("dd/MM/yyyy HH:mm"); dateFormater.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); return dateFormater.format(date); }
From source file:contestWebsite.MainPage.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets"); ve.init();/*from w w w.j a v a2s .com*/ VelocityContext context = new VelocityContext(); Pair<Entity, UserCookie> infoAndCookie = init(context, req); UserCookie userCookie = infoAndCookie.y; Entity user = userCookie != null ? userCookie.authenticateUser() : null; boolean loggedIn = (boolean) context.get("loggedIn"); if (!loggedIn && req.getParameter("refresh") != null && req.getParameter("refresh").equals("1")) { resp.sendRedirect("/?refresh=1"); } if (loggedIn) { if (!userCookie.isAdmin()) { String username = (String) user.getProperty("user-id"); String name = (String) user.getProperty("name"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, username)); Entity reg = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0); ArrayList<String> regData = new ArrayList<String>(); Map<String, Object> props = reg.getProperties(); for (Entry<String, Object> prop : props.entrySet()) { String key = prop.getKey(); if (!key.equals("account") && !key.equals("cost") && PropNames.names.get(key) != null && !prop.getValue().equals("")) { regData.add("<dt>" + PropNames.names.get(key) + "</dt>\n<dd>" + prop.getValue() + "</dd>"); } } Entity contestInfo = infoAndCookie.x; String endDateStr = (String) contestInfo.getProperty("editEndDate"); String startDateStr = (String) contestInfo.getProperty("editStartDate"); Date endDate = new Date(); Date startDate = new Date(); try { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+6")); endDate = dateFormat.parse(endDateStr); startDate = dateFormat.parse(startDateStr); } catch (ParseException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format"); } if (new Date().after(endDate) || new Date().before(startDate)) { context.put("regEditClosed", true); } Collections.sort(regData); context.put("regData", regData); context.put("level", contestTabulation.Level.fromString(props.get("schoolLevel").toString())); context.put("studentData", unescapeHtml4(((Text) props.get("studentData")).getValue())); context.put("price", contestInfo.getProperty("price")); context.put("name", name); context.put("user", user.getProperty("user-id")); context.put("updated", req.getParameter("updated")); } else { context.put("error", req.getParameter("error")); context.put("user", user.getProperty("user-id")); context.put("name", "Contest Administrator"); context.put("admin", true); } context.put("complete", infoAndCookie.x.getProperty("complete")); context.put("testDownloadURL", infoAndCookie.x.getProperty("testDownloadURL")); } else { Yaml yaml = new Yaml(); ArrayList<ArrayList<String>> slideshow = (ArrayList<ArrayList<String>>) yaml .load(((Text) infoAndCookie.x.getProperty("slideshow")).getValue()); context.put("slideshow", slideshow); } context.put("esc", new EscapeTool()); context.put("aboutText", ((Text) infoAndCookie.x.getProperty("aboutText")).getValue()); context.put("siteVerification", infoAndCookie.x.getProperty("siteVerification")); close(context, ve.getTemplate("main.html"), resp); }
From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java
private static Timestamp timestamp(String utcDateTime) { if (utcDateTime == null) { return null; }//from w ww .ja va 2 s. co m SimpleDateFormat formatter = new SimpleDateFormat(TimeUtils.PATTERN_UTC); formatter.setTimeZone(TimeUtils.TIMEZONE_UTC); try { Date date = formatter.parse(utcDateTime); return new Timestamp(date.getTime()); } catch (ParseException e) { if (log.isErrorEnabled()) { log.error("Failed to parse date/time " + utcDateTime); } return null; } }
From source file:com.stanley.captioner.MainFrame.java
private Object[] getVideoInfo(File file) { String path = file.getAbsolutePath(); Converter converter = new Converter(); FFprobe ffprobe = null;//from www. jav a 2s .co m try { ffprobe = new FFprobe(converter.getFFprobePath()); } catch (IOException e) { System.out.println("Failed to find ffprobe."); } FFmpegProbeResult probeResult = null; try { probeResult = ffprobe.probe(path); } catch (IOException e) { System.out.println("Failed to probe video file."); } FFmpegFormat format = probeResult.getFormat(); FFmpegStream stream = probeResult.getStreams().get(0); String type = FilenameUtils.getExtension(path).toUpperCase(); String size = NumberFormat.getNumberInstance(Locale.US).format(file.length() / 1000) + " KB"; long millis = stream.duration_ts * 1000; TimeZone tz = TimeZone.getTimeZone("UTC"); SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); df.setTimeZone(tz); String duration = df.format(new Date(millis)); return new Object[] { format.filename, type, size, duration, stream.codec_name, stream.width, stream.height }; }
From source file:executor.TesterMain.java
public void start(IStrategy strategy) throws Exception { // get the instance of the IClient interface final ITesterClient client = TesterFactory.getDefaultInstance(); // set the listener that will receive system events if (StringUtils.isNotEmpty(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_START))) { final SimpleDateFormat dateFormat = new SimpleDateFormat( PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_FORMAT)); dateFormat.setTimeZone( TimeZone.getTimeZone(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_TIMEZONE))); Date dateFrom = dateFormat.parse(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_START)); Date dateTo = dateFormat.parse(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_END)); client.setDataInterval(DataLoadingMethod.DIFFERENT_PRICE_TICKS, dateFrom.getTime(), dateTo.getTime()); }/* w w w . j ava2 s .c om*/ final String strategyName = strategy.getClass().getName(); client.setSystemListener(new ISystemListener() { @Override public void onStart(long processId) { LOGGER.info("Strategy started: " + processId); } @Override public void onStop(long processId) { LOGGER.info("Strategy stopped: " + processId); SimpleDateFormat sdf = new SimpleDateFormat( PropertyHandler.getProperty(StrategyProperties.REPORTER_CURRENT_REPORT_FORMAT)); String propertyFolder = PropertyHandler .getProperty(StrategyProperties.REPORTER_CURRENT_REPORT_OUTPUT_DIRECTORY); File reportFile; if (Boolean.parseBoolean( PropertyHandler.getProperty(StrategyProperties.REPORTER_CURRENT_REPORT_OVERWRITABLE))) { reportFile = new File(propertyFolder + strategyName + ".html"); } else { reportFile = new File( propertyFolder + sdf.format(GregorianCalendar.getInstance().getTime()) + ".html"); } try { client.createReport(processId, reportFile); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } if (client.getStartedStrategies().size() == 0) { System.exit(0); } } @Override public void onConnect() { LOGGER.info("Connected"); } @Override public void onDisconnect() { // tester doesn't disconnect } }); LOGGER.info("Connecting..."); // connect to the server using jnlp, user name and password // connection is needed for data downloading client.connect("https://www.dukascopy.com/client/demo/jclient/jforex.jnlp", PropertyHandler.getProperty(StrategyProperties.CLIENT_USERNAME), PropertyHandler.getProperty(StrategyProperties.CLIENT_PASSWORD)); // wait for it to connect int i = 10; // wait max ten seconds while (i > 0 && !client.isConnected()) { Thread.sleep(1000); i--; } if (!client.isConnected()) { LOGGER.error("Failed to connect Dukascopy servers"); System.exit(1); } // set instruments that will be used in testing for (String anInstrument : PropertyHandler.getProperty(StrategyProperties.CLIENT_INSTRUMENTS_USED) .split(",")) { instrumentsToAdd.add(Instrument.fromString(anInstrument)); } final Set<Instrument> instruments = new HashSet<>(); instruments.addAll(instrumentsToAdd); LOGGER.info("Subscribing instruments..."); client.setSubscribedInstruments(instruments); // setting initial deposit client.setInitialDeposit( Instrument .fromString(PropertyHandler.getProperty(StrategyProperties.CLIENT_DEPOSIT_INITIAL_CURRENCY)) .getSecondaryJFCurrency(), Double.parseDouble(PropertyHandler.getProperty(StrategyProperties.CLIENT_DEPOSIT_INITIAL_AMOUNT))); // load data LOGGER.info("Downloading data"); Future<?> future = client.downloadData(null); // wait for downloading to complete future.get(); // start the strategy LOGGER.info("Starting strategy"); // executor.MA_Play strategy = new executor.MA_Play(); // OrderLifeManagement strategy = new OrderLifeManagement(); // WinnerStrategy strategy = new WinnerStrategy(); // ModifiedWinnerStrategy strategy = new ModifiedWinnerStrategy(); // HourToCsv strategy = new HourToCsv(dateFrom, dateTo); client.startStrategy(strategy, new LoadingProgressListener() { @Override public void dataLoaded(long startTime, long endTime, long currentTime, String information) { LOGGER.info(information); } @Override public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) { } @Override public boolean stopJob() { return false; } }); // now it's running }
From source file:at.rocworks.oa4j.logger.dbs.NoSQLMongoDB.java
@Override public boolean dpGetPeriod(Date t1, Date t2, Dp dp, Set<String> configs, DpGetPeriodResult result) { // db.events.find({tag: "System1:Test_1_1.Value", ts: {$gt: ISODate("2016-07-28T09:00:00.000Z"), $lt: ISODate("2016-07-28T10:00:00.000Z")}}, {_id:0, tag:1, ts:1}); JDebug.out.log(Level.INFO, "dpGetPeriod {0}-{1} dp={2} configs={3}", new Object[] { t1, t2, dp, configs.toString() }); final SimpleDateFormat fmt = new SimpleDateFormat(TimeVar.FMT_DATE_JS_MS); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); // columns//from www .ja v a 2s .c o m final ArrayList<Dp> dps = createDpConfigAttrList(dp, configs); if (dps.isEmpty()) { JDebug.out.warning("dpGetPeriod without any valid config."); return false; } Document columns = new Document(); columns.append("_id", 0); columns.append("ts", 1); dps.forEach((Dp x) -> { String c = attrMap.get(x.getAttribute()); if (c != null) columns.append(c, 1); }); // filter Document query = new Document(); query.append("tag", getTagOfDp(dp)); query.append("ts", new Document("$gte", t1).append("$lte", t2)); // query FindIterable<Document> find = evcoll.find(query); find.projection(columns); find.forEach((Block<Document>) document -> { // { "ts" : { "$date" : 1469696660635 }, "value" : { "number" : 3.0 }, "status" : { "$numberLong" : "-9007199254738370303" }, "user" : 0 } //JDebug.out.info(document.toJson()); Date ts = document.getDate("ts"); Object value; for (int i = 0; i < dps.size(); i++) { try { final Dp attr = dps.get(i); switch (attr.getAttribute()) { case Value: // value_number value = document.get("value"); if (value instanceof Document) { Document dval = (Document) value; dval.keySet().forEach(type -> result.addValue(attr, ts, dval.get(type))); } break; case Status: value = document.get("status"); result.addVariable(attr, ts, new Bit32Var(value)); break; case Status64: value = document.get("status"); result.addVariable(attr, ts, new Bit64Var(value)); break; case Manager: value = document.get("manager"); result.addVariable(attr, ts, Variable.newVariable(value)); break; case User: value = document.get("user"); result.addVariable(attr, ts, Variable.newVariable(value)); break; case Stime: value = ts; result.addVariable(attr, ts, Variable.newVariable(value)); break; default: JDebug.out.log(Level.SEVERE, "unhandeled config {0}", attr.getAttribute()); } } catch (Exception ex) { JDebug.StackTrace(Level.SEVERE, ex); } } }); return true; }
From source file:co.uk.randompanda30.sao.modules.util.BackupUtil.java
public BackupUtil() { if (Config.ConfigValues.BACKUP_PATHTOBACKUP.value.toString().equalsIgnoreCase("changeme") || Config.ConfigValues.BACKUP_PATHTOSTORE.value.toString().equalsIgnoreCase("changeme") || Config.ConfigValues.BACKUP_TOSTORELOGS.value.toString().equalsIgnoreCase("changeme")) { // Some warning here return;/*from w w w.jav a2s .c o m*/ } toBackup = Config.ConfigValues.BACKUP_PATHTOBACKUP.value + (Config.ConfigValues.BACKUP_PATHTOBACKUP.value.toString().endsWith("/") ? "" : "/"); toStore = Config.ConfigValues.BACKUP_PATHTOSTORE.value + (Config.ConfigValues.BACKUP_PATHTOSTORE.value.toString().endsWith("/") ? "" : "/"); toStoreLogs = Config.ConfigValues.BACKUP_TOSTORELOGS.value + (Config.ConfigValues.BACKUP_TOSTORELOGS.value.toString().endsWith("/") ? "" : "/"); SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy-HH:mm:ss-z"); f.setTimeZone(TimeZone.getTimeZone("Europe/London")); time = f.format(GregorianCalendar.getInstance().getTime()); if (!new File(toStore).exists()) { new File(toStore).mkdir(); } String time = (String) Config.ConfigValues.BACKUP_DELAY.value; String[] splitter = { time }; int days = 0; int hours = 0; int minutes = 0; int seconds = 0; if (!time.contains("d") && !time.contains("h") && !time.contains("m") && !time.contains("s")) { if (NumberUtil.isNumber(time)) { minutes = NumberUtil.getNumber(time); } else { time = "0"; } } else { if (time.contains("d")) { splitter = splitter[0].split("d"); days = NumberUtil.getNumber(splitter[0]); if (splitter.length == 2) { splitter[0] = splitter[1]; } } if (time.contains("h")) { splitter = splitter[0].split("h"); hours = NumberUtil.getNumber(splitter[0]); if (splitter.length == 2) { splitter[0] = splitter[1]; } } if (time.contains("m")) { splitter = splitter[0].split("m"); minutes = NumberUtil.getNumber(splitter[0]); if (splitter.length == 2) { splitter[0] = splitter[1]; } } if (time.contains("s")) { splitter = splitter[0].split("s"); seconds = NumberUtil.getNumber(splitter[0]); } if (time.equals("0")) { // Message here } delay = (days * 1000 * 60 * 60 * 24) + (hours * 1000 * 60 * 60) + (minutes * 1000 * 60) + (seconds * 1000); } if (!TEMP.backupc.contains("lastbackup")) { TEMP.backupc.set("lastbackup", System.currentTimeMillis()); CBackup.save(); backup(); } else { startTimer(); } }
From source file:net.sf.logsaw.dialect.log4j.pattern.Log4JConversionPatternTranslator.java
@Override public void applyTimeZone(TimeZone tz, List<ConversionRule> rules) { for (ConversionRule rule : rules) { if (rule.getPlaceholderName().equals("d")) { //$NON-NLS-1$ SimpleDateFormat df = rule.getProperty(PROP_DATEFORMAT, SimpleDateFormat.class); Assert.isNotNull(df, "dateFormat"); //$NON-NLS-1$ df.setTimeZone(tz); return; }/* w w w . j a v a2s .c o m*/ } }
From source file:com.weibo.net.Weibo.java
protected static Date parseDate(String str, String format) throws WeiboException { if (str == null || "".equals(str)) { return null; }//from w w w. ja v a 2 s. co m SimpleDateFormat sdf = formatMap.get(format); if (null == sdf) { sdf = new SimpleDateFormat(format, Locale.ENGLISH); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); formatMap.put(format, sdf); } try { synchronized (sdf) { // SimpleDateFormat is not thread safe return sdf.parse(str); } } catch (ParseException pe) { throw new WeiboException("Unexpected format(" + str + ") returned from sina.com.cn"); } }
From source file:com.derbysoft.common.log4j.DailyRollingFileAppender.java
int computeCheckPeriod() { RollingCalendar rollingCalendar = new RollingCalendar(timeZone, Locale.getDefault()); // set sate to 1970-01-01 00:00:00 GMT Date epoch = new Date(0); if (datePattern != null) { for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern); simpleDateFormat.setTimeZone(timeZone); // do all date formatting in GMT String r0 = simpleDateFormat.format(epoch); rollingCalendar.setType(i);//from w ww .j av a 2 s. c om Date next = new Date(rollingCalendar.getNextCheckMillis(epoch)); String r1 = simpleDateFormat.format(next); //System.out.println("Type = "+i+", r0 = "+r0+", r1 = "+r1); if (r0 != null && r1 != null && !r0.equals(r1)) { return i; } } } return TOP_OF_TROUBLE; // Deliberately head for trouble... }