Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

In this page you can find the example usage for java.util Date setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:com.eviware.loadui.impl.statistics.db.util.TypeConverter.java

public static Object stringToObject(String value, Class<? extends Object> type) throws IOException {
    if (value == null) {
        return null;
    } else if (type == Long.class) {
        return Long.valueOf(value);
    } else if (type == Integer.class) {
        return Integer.valueOf(value);
    } else if (type == Double.class) {
        return Double.valueOf(value);
    } else if (type == Float.class) {
        return Float.valueOf(value);
    } else if (type == Boolean.class) {
        return Boolean.valueOf(value);
    } else if (type == String.class) {
        return value;
    } else if (type == Date.class) {
        Date d = new Date();
        d.setTime(Long.valueOf(value));
        return d;
    } else if (type == BufferedImage.class) {
        return imageFromByteArray(Base64.decodeBase64(value));
    } else {// www .  ja  v a  2s  .c o  m
        try {
            type.asSubclass(Serializable.class);
            return base64ToObject(value);
        } catch (Exception e) {
            return value;
        }
    }
}

From source file:pt.lsts.neptus.plugins.sunfish.awareness.PositionHistory.java

public static Collection<AssetPosition> getHistory() throws Exception {

    try {/*from w  ww . j av a  2s.co  m*/
        downloadData();
    } catch (Exception e) {
        e.printStackTrace();
    }

    Vector<AssetPosition> positions = new Vector<>();
    SimpleDateFormat dayFormat = new SimpleDateFormat("YYYY-MM-dd");
    Date current = new Date();
    Date d = new Date();
    for (int i = 30; i >= 0; i--) {
        d.setTime(current.getTime() - i * (1000 * 24 * 3600));
        String day = dayFormat.format(d);
        downloadCsv(day, false);
        BufferedReader reader = new BufferedReader(new FileReader("positions/" + day));
        String line;

        while ((line = reader.readLine()) != null) {
            String parts[] = line.split(",");
            if (parts.length < 4)
                continue;
            try {
                Date time = fmt2.parse(parts[0]);
                String id = parts[1].trim().toLowerCase();
                double lat_degs = Double.parseDouble(parts[2].trim());
                double lon_degs = Double.parseDouble(parts[3].trim());
                AssetPosition position = new AssetPosition(id, lat_degs, lon_degs);
                position.setTimestamp(time.getTime());
                if (id.toLowerCase().startsWith("spot"))
                    position.setType("Spot Tag");
                else if (id.toLowerCase().startsWith("argos"))
                    position.setType("Argos Tag");

                positions.add(position);
            } catch (Exception e) {
                NeptusLog.pub().error("Error parsing history line: " + line);
            }
        }
        reader.close();
    }
    return positions;
}

From source file:com.mvdb.etl.actions.InitCustomerData.java

private static void initData(final OrderDAO orderDAO, final int batchCount, final int batchSize,
        final Date startDate, final Date endDate) {

    for (int batchIndex = 0; batchIndex < batchCount; batchIndex++) {
        final int batchIndexFinal = batchIndex;
        TimedExecutor te = new TimedExecutor() {

            @Override/*ww w  .  j  a v a 2  s .c  o m*/
            public void execute() {

                List<Order> orders = new ArrayList<Order>();
                for (int recordIndex = 0; recordIndex < batchSize; recordIndex++) {
                    Date createDate = RandomUtil.getRandomDateInRange(startDate, endDate);
                    Date updateDate = new Date();
                    updateDate.setTime(createDate.getTime());
                    Order order = new Order(orderDAO.getNextSequenceValue(), RandomUtil.getRandomString(5),
                            RandomUtil.getRandomInt(), createDate, updateDate);
                    orders.add(order);
                }
                orderDAO.insertBatch(orders);
                System.out.println(String.format("Completed Batch %d of %d where size of batch is %s",
                        batchIndexFinal + 1, batchCount, batchSize));
            }

        };
        long runTime = te.timedExecute();
        System.out.println("Ran for seconds: " + runTime / 1000);
    }

}

From source file:org.nodatime.tzvalidate.Java7Dump.java

/**
 * Work out the next transition from the given starting point, in the given time zone.
 * This checks each day until END, and assumes there is no more than one transition per day.
 * Once it's found a day containing a transition, it performs a binary search to find the actual
 * time of the transition./*from  w w  w .ja v a 2  s  .  com*/
 * Unfortunately, java.util.TimeZone doesn't provide a cleaner approach than this :(
 */
private static Long getNextTransition(TimeZone zone, long start, long end) {
    long startOffset = zone.getOffset(start);
    boolean startDaylight = zone.inDaylightTime(new Date(start));

    long now = start + ONE_DAY_MILLIS;
    Date nowDate = new Date();

    // Inclusive upper bound to enable us to find transitions within the last day.
    while (now <= end) {
        nowDate.setTime(now);
        if (zone.getOffset(now) != startOffset || zone.inDaylightTime(nowDate) != startDaylight) {
            // Right, so there's a transition strictly after now - ONE_DAY_MILLIS, and less than or equal to now. Binary search...
            long upperInclusive = now;
            long lowerExclusive = now - ONE_DAY_MILLIS;
            while (upperInclusive > lowerExclusive + 1) {
                // The values will never be large enough for this addition to be a problem.
                long candidate = (upperInclusive + lowerExclusive) / 2;
                nowDate.setTime(candidate);
                if (zone.getOffset(candidate) != startOffset || zone.inDaylightTime(nowDate) != startDaylight) {
                    // Still seeing a difference: look earlier
                    upperInclusive = candidate;
                } else {
                    // Same as at start of day: look later
                    lowerExclusive = candidate;
                }
            }
            // If we turn out to have hit the end point, we're done without a final transition. 
            return upperInclusive == end ? null : upperInclusive;
        }
        now += ONE_DAY_MILLIS;
    }
    return null;
}

From source file:dataflow.feed.api.Weather.java

/**
 * Method which connects to the weather API and retrieves the weather from the day before today
 *//*from   ww  w.ja  va 2 s.  c om*/
public static void getWeather() {
    String key = "c6aee37b80d801b44279ac16374db";
    Calendar fromTime = Calendar.getInstance();
    Date weatherDate = new Date();
    for (int i = 1; i < 7; i++) {
        weatherDate.setTime(weatherDate.getTime() - (86400000));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(weatherDate);
        String jsonString = callURL(
                "https://api.worldweatheronline.com/free/v2/past-weather.ashx?q=Rotterdam&format=json&tp=24&key=c6aee37b80d801b44279ac16374db&date="
                        + date);
        try {
            MySQLDb db = new MySQLDb();
            JSONObject jsonObject = new JSONObject(jsonString).getJSONObject("data");
            db.insertWeather(date, jsonObject);
        } catch (JSONException e) {
            throw e;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException ex) {
            Logger.getLogger(Weather.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:pt.lsts.neptus.plugins.sunfish.awareness.PositionHistory.java

public static void downloadData() throws Exception {
    Date d = new Date();
    SimpleDateFormat dayFormat = new SimpleDateFormat("YYYY-MM-dd");
    downloadCsv(dayFormat.format(d), true);
    for (int i = 0; i < 30; i++) {
        d.setTime(d.getTime() - 1000 * 24 * 3600);
        String day = dayFormat.format(d);
        if (i == 0)
            downloadCsv(day, true);/*  w  w w  .jav  a2 s  .c o m*/
        else
            downloadCsv(day, false);
    }
}

From source file:mini_mirc_client.Mini_mirc_client.java

public static void showMsg() {
    try {//  w  w w . j a v a  2s .  c  o  m
        synchronized (allMsg) {

            if (!allMsg.isEmpty() && allMsg.size() > 0) {
                for (int i = 0; i < allMsg.size(); i++) {
                    JSONObject temp = (JSONObject) allMsg.get(i);
                    JSONArray tempArr = (JSONArray) temp.get("msg");

                    for (int j = 0; j < tempArr.size(); j++) {
                        temp = (JSONObject) tempArr.get(j);
                        SimpleDateFormat formatDate = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

                        Date sendDat = new Date();
                        sendDat.setTime((long) temp.get("timestamp"));

                        System.out
                                .println(">> [" + temp.get("channel").toString() + "] [" + temp.get("username")
                                        + "] " + temp.get("message") + " || " + formatDate.format(sendDat));
                    }
                }
            }
            allMsg.clear();
        }
    } catch (Exception E) {
        E.printStackTrace();
    }
}

From source file:com.soomla.data.RewardStorage.java

public static Date getLastGivenTime(String rewardId) {
    long timeMillis = getLastGivenTimeMillis(rewardId);
    if (timeMillis == 0) {
        return null;
    }/*from   w  w w.java 2s  .  c om*/
    Date toReturn = new Date();
    toReturn.setTime(timeMillis);
    return toReturn;
}

From source file:controllers.CNBCProxy.java

private static String CalculateDateFormat(long millis) {
    // Set helping arrays
    String[] monthArr = new String[12];
    String[] dayArr = new String[7];

    // Set month names
    monthArr[0] = "January";
    monthArr[1] = "February";
    monthArr[2] = "March";
    monthArr[3] = "April";
    monthArr[4] = "May";
    monthArr[5] = "June";
    monthArr[6] = "July";
    monthArr[7] = "August";
    monthArr[8] = "September";
    monthArr[9] = "October";
    monthArr[10] = "November";
    monthArr[11] = "December";

    // Set day names
    dayArr[0] = "Sunday";
    dayArr[1] = "Monday";
    dayArr[2] = "Tuesday";
    dayArr[3] = "Wednesday";
    dayArr[4] = "Thursday";
    dayArr[5] = "Friday";
    dayArr[6] = "Saturday";

    /** Create Date object with random date, in order to calculate date of article like 
    the "setTime()" function in Javascript (date since January 1, 1970 00:00:00 gmt)
    **//*from w w w  .j  ava 2 s  . c  o m*/

    Date dateObj = new Date(92, 1, 10);

    // Add long number to get article's date
    dateObj.setTime(millis);

    StringBuilder date = new StringBuilder();
    date.append(dayArr[dateObj.getDay()]).append(", ").append(Integer.toString(dateObj.getDate())).append(" ")
            .append(monthArr[dateObj.getMonth()]).append(" ").append(Integer.toString(dateObj.getYear() + 1900))
            .append(" "); // 1900 added to year(see getYear() method's documentation)

    String hours;
    String midnight;

    if (dateObj.getHours() > 12) {
        if (dateObj.getHours() - 12 < 10) {
            hours = "0" + Integer.toString(dateObj.getHours() - 12);
        } else {
            hours = Integer.toString(dateObj.getHours() - 12);
        }
        midnight = "PM";
    } else {
        if (dateObj.getHours() < 10) {
            hours = "0" + Integer.toString(dateObj.getHours());
        } else {
            hours = Integer.toString(dateObj.getHours());
        }
        midnight = "AM";
    }

    date.append(hours).append(":").append(Integer.toString(dateObj.getMinutes()))
            .append(" " + midnight + " ET");

    return date.toString();
}

From source file:netflow.Main.java

private static long importFile(String fileName, StringTokenizerParser p, boolean processAllFile)
        throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    int lines = 0;
    int comments = 0;
    int goodLines = 0;
    int oldlines = 0;
    String line;/*from  w  w  w .j a  v  a  2s  .com*/
    DateFormat df = new SimpleDateFormat("HH:mm:ss EEE dd MMM yyyy", Locale.ENGLISH);
    long now = System.currentTimeMillis();
    Date guard = new Date();
    log.info("Begin process " + guard);
    Date last = DatabaseProxy.getInstance().getMaxDate();
    if (last == null) {
        log.info("Date empty. Creating a new one");
        last = new Date();
        last.setTime(0L);
    }
    Date newDate = guard;
    log.info(last);

    HostCache cache = HostCache.getInstance();
    LineProcessor processor = new LineProcessor(cache);
    while ((line = reader.readLine()) != null) {
        if (!line.startsWith("#")) {
            if (last.before(newDate) || processAllFile) {
                String[] elements = p.parseLine(line);
                processor.parseLine(elements);
                goodLines++;
            } else {
                oldlines++;
            }
        } else {
            comments++;

            if (line.startsWith("#Time")) {
                newDate = LineProcessor.parseTime(line, df);
                log.info("Saving hosts " + newDate);
            }

            if (line.startsWith("#EndData") && !cache.isEmpty() && newDate != null && !newDate.equals(guard)) {
                log.info("Saving hosts (finish processing) " + newDate);
                cache.save(newDate);
            }
        }
        lines++;
    }
    log.info(lines + " Comments: " + comments + ", Effective lines: " + goodLines + ", Old lines:" + oldlines);
    return now;
}