Example usage for java.util Calendar setTimeInMillis

List of usage examples for java.util Calendar setTimeInMillis

Introduction

In this page you can find the example usage for java.util Calendar setTimeInMillis.

Prototype

public void setTimeInMillis(long millis) 

Source Link

Document

Sets this Calendar's current time from the given long value.

Usage

From source file:cn.com.sunjiesh.wechat.handler.WechatMaterialHandler.java

/**
 * ????//from   w ww.  jav  a2  s  .c o  m
 *
 * @param offset ?????0?? 
 * @param count ????120
 * @param accessToken
 * @return ???
 * @throws ServiceException ServiceException
 */
public static BatchgetMaterialNews batchgetMaterialNews(int offset, int count, String accessToken)
        throws ServiceException {
    String type = "news";
    JSONObject responseJson = batchgetMaterial(offset, count, type, accessToken);

    //?BatchgetMaterial
    BatchgetMaterialNews batchgetMaterial = new BatchgetMaterialNews();
    int totalCount = responseJson.getIntValue("total_count");
    int itemCount = responseJson.getIntValue("item_count");
    batchgetMaterial.setTotalCount(totalCount);
    batchgetMaterial.setItemCount(itemCount);
    JSONArray itemArr = responseJson.getJSONArray("item");
    for (int index = 0; index < itemArr.size(); index++) {
        JSONObject itemJson = itemArr.getJSONObject(index);
        String mediaId = itemJson.getString("media_id");
        Long updateTime = itemJson.getLong("update_time");
        JSONObject contentJson = itemJson.getJSONObject("content");
        JSONArray newsItemArr = contentJson.getJSONArray("news_item");
        List<MaterialNewsResponse> mediaList = new ArrayList<>();
        for (int newsItemIndex = 0; newsItemIndex < newsItemArr.size(); newsItemIndex++) {
            JSONObject newsItemJson = newsItemArr.getJSONObject(newsItemIndex);
            MaterialNewsResponse media = jsonObjToMateriaNews(newsItemJson);
            mediaList.add(media);
        }
        Calendar updateTimeCal = Calendar.getInstance();
        updateTimeCal.setTimeInMillis(updateTime);
        BatchgetMaterialItemContent batchgetMaterialItemContent = new BatchgetMaterialItemContent();
        batchgetMaterialItemContent.setNewsList(mediaList);
        BatchgetMaterialNewsItem item = new BatchgetMaterialNewsItem();
        item.setMediaId(mediaId);
        item.setContent(batchgetMaterialItemContent);
        item.setUpdateTime(updateTimeCal.getTime());

    }

    return batchgetMaterial;
}

From source file:cn.com.sunjiesh.wechat.handler.WechatMaterialHandler.java

/**
 * ?????/* w  ww  .j  a  v  a 2s. c  o m*/
 *
 * @param type ??image?video? voice?news
 * @param offset ?????0?? 
 * @param count ????120
 * @return ????
 * @throws ServiceException ServiceException
 */
public static BatchgetMaterialOther batchgetMaterialOther(String type, int offset, int count,
        String accessToken) throws ServiceException {

    //??
    if (offset < 0) {
        throw new ServiceException("offset??0");
    }
    if (count < 1 || count > 20) {
        throw new ServiceException("count??1-20");
    }

    JSONObject responseJson = batchgetMaterial(offset, count, type, accessToken);
    //?BatchgetMaterial
    BatchgetMaterialOther batchgetMaterial = new BatchgetMaterialOther();
    int totalCount = responseJson.getIntValue("total_count");
    int itemCount = responseJson.getIntValue("item_count");
    batchgetMaterial.setTotalCount(totalCount);
    batchgetMaterial.setItemCount(itemCount);
    JSONArray itemArr = responseJson.getJSONArray("item");
    for (int index = 0; index < itemArr.size(); index++) {
        JSONObject itemJson = itemArr.getJSONObject(index);
        String mediaId = itemJson.getString("media_id");
        Long updateTime = itemJson.getLong("update_time");
        String name = itemJson.getString("name");
        String url = itemJson.getString("url");

        Calendar updateTimeCal = Calendar.getInstance();
        updateTimeCal.setTimeInMillis(updateTime);
        BatchgetMaterialOtherItem item = new BatchgetMaterialOtherItem();
        item.setMediaId(mediaId);
        item.setUpdateTime(updateTimeCal.getTime());
        item.setUrl(url);
        item.setName(name);
        batchgetMaterial.getItemList().add(item);
    }

    return batchgetMaterial;
}

From source file:com.icesoft.tutorial.TimeZoneBean.java

public static String formatCurrentTime(DateFormat dateFormat) {
    Calendar cal = dateFormat.getCalendar();
    cal.setTimeInMillis(System.currentTimeMillis());
    return dateFormat.format(cal.getTime());
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Checks if a timestamp (ms) is in the current month
 *
 * @param when a ms timestamp/* ww w. j a  v a  2  s  .c  o m*/
 * @return <code>true</code> if it is <code>false</code> otherwise
 */
public static boolean isSameMonth(long when) {
    Calendar tmp = Calendar.getInstance();
    tmp.setTimeInMillis(when);

    // cal.get(FIELD) does not work :( fields are not recomputed
    int thenYear = tmp.get(Calendar.YEAR);
    int thenMonth = tmp.get(Calendar.MONTH);

    tmp.setTimeInMillis(System.currentTimeMillis());
    int nowYear = tmp.get(Calendar.YEAR);
    int nowMonth = tmp.get(Calendar.MONTH);

    Log.d(TAG, "comparing: " + nowMonth + "." + nowYear + " / " + thenMonth + "." + thenYear);
    return (thenYear == nowYear) && (thenMonth == nowMonth);
}

From source file:lu.lippmann.cdb.common.gui.ts.TimeSeriesChartUtil.java

public static ChartPanel buildChartPanelForNominalAttribute(final Instances ds, final Attribute attr,
        final int dateIdx) {
    final TaskSeriesCollection localTaskSeriesCollection = new TaskSeriesCollection();
    final java.util.List<String> names = new ArrayList<String>();

    final Set<String> present = WekaDataStatsUtil.getPresentValuesForNominalAttribute(ds, attr.index());
    for (final String pr : present) {
        names.add(pr);//  ww  w  .  jav a  2s. com
        localTaskSeriesCollection.add(new TaskSeries(pr));
    }

    final Calendar cal = Calendar.getInstance();
    try {
        for (final double[] dd : WekaTimeSeriesUtil.split(ds, attr.index())) {
            cal.setTimeInMillis((long) dd[0]);
            final Date start = cal.getTime();
            cal.setTimeInMillis((long) dd[1]);
            final Date end = cal.getTime();
            final String sd = ds.instance((int) dd[2]).stringValue(attr);
            localTaskSeriesCollection.getSeries(sd).add(new Task("T", start, end));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    final XYTaskDataset localXYTaskDataset = new XYTaskDataset(localTaskSeriesCollection);
    localXYTaskDataset.setTransposed(true);
    localXYTaskDataset.setSeriesWidth(0.6D);

    final DateAxis localDateAxis = new DateAxis(DATE_TIME_LABEL);
    final SymbolAxis localSymbolAxis = new SymbolAxis("", names.toArray(new String[names.size()]));
    localSymbolAxis.setGridBandsVisible(false);
    final XYBarRenderer localXYBarRenderer = new XYBarRenderer();
    localXYBarRenderer.setUseYInterval(true);
    localXYBarRenderer.setShadowVisible(false);
    final XYPlot localXYPlot = new XYPlot(localXYTaskDataset, localDateAxis, localSymbolAxis,
            localXYBarRenderer);

    final CombinedDomainXYPlot localCombinedDomainXYPlot = new CombinedDomainXYPlot(
            new DateAxis(DATE_TIME_LABEL));
    localCombinedDomainXYPlot.add(localXYPlot);
    final JFreeChart localJFreeChart = new JFreeChart("", localCombinedDomainXYPlot);
    localJFreeChart.setBackgroundPaint(Color.white);

    final ChartPanel cp = new ChartPanel(localJFreeChart, true);
    cp.setBorder(new TitledBorder(attr.name()));
    return cp;
}

From source file:net.mumie.coursecreator.graph.MetaInfos.java

public static Calendar newCalendar(long millis) {
    Calendar cal = Calendar.getInstance();
    cal.setLenient(true);//from w  w  w  . j  a va 2 s .c  o  m
    cal.setTimeInMillis(millis);
    return cal;
}

From source file:com.projity.script.object.TimeIntervals.java

public static TimeWindow generateWindow(long start, int scale, int sign) {
    int timeType, timeType2 = 0, number2;
    int timeIncrement = 1, timeIncrement2 = 1;
    switch (scale) {
    case TimeIntervals.DAY:
        timeType = Calendar.DAY_OF_MONTH;
        timeType2 = Calendar.WEEK_OF_YEAR;
        break;/* w w  w  .ja va  2  s .c  om*/
    case TimeIntervals.WEEK:
        timeType = Calendar.WEEK_OF_YEAR;
        timeType2 = Calendar.MONTH;
        break;
    case TimeIntervals.MONTH:
        timeType = Calendar.MONTH;
        timeType2 = Calendar.MONTH;
        timeIncrement2 = 3;
        break;
    case TimeIntervals.QUARTER:
        timeType = Calendar.MONTH;
        timeType2 = Calendar.YEAR;
        timeIncrement = 3;
        break;
    case TimeIntervals.YEAR:
        timeType = Calendar.YEAR;
        timeType2 = Calendar.YEAR;
        break;
    default:
        return null;
    }

    Calendar c = Calendar.getInstance(DateUtils.UTC_TIME_ZONE, Locale.US);//DateTime.calendarInstance();
    c.setTimeInMillis(start);

    //adapt start
    floorCal(scale, c);
    long s1 = c.getTimeInMillis();
    floorCal(scale + 1, c);
    long s2 = c.getTimeInMillis();

    c.setTimeInMillis(s1);
    long s;
    while ((s = c.getTimeInMillis()) >= s2) { //can occur with week, month scale
        s1 = s;
        c.add(timeType, -timeIncrement);
    }

    //set approximative end
    c.setTimeInMillis(s1);
    c.add(timeType, sign * timeIncrement * WINDOW_INTERVALS);
    TimeWindow win = new TimeWindow();
    if (sign > 0)
        win.setS(s1);
    else
        win.setE(s1);
    if (sign > 0)
        win.setE(c.getTimeInMillis());
    else
        win.setS(c.getTimeInMillis());
    return win;
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java

/***
 * Used to parse, escape and enrich Kissmetircs Json records
 * //  ww  w.ja va2s.c  o m
 * @param rawJsonRow
 * @param fileNameInputToMapper
 * @return
 */
public static KeyRowWrapper parseJsonRowToValidJson(Text rawJsonRow, String fileNameInputToMapper,
        String filePath) {

    String jsonString = "";
    boolean wasOctalParsingNeeded = false;

    try {
        System.setProperty("file.encoding", "UTF-8");
        s = rawJsonRow.toString();
        Charset charSet = Charset.forName("UTF-8");
        byte[] encoded = s.getBytes(charSet);
        decodedStrRaw = new String(encoded, charSet);

        // Test new Apache Lang3
        // decodedStr = StringEscapeUtils.unescapeJava(decodedStr);

        //Replace any remaining Octal encoded Characters
        decodedStrParsed = replaceOctalUft8Char(decodedStrRaw);
        if (decodedStrParsed.compareTo(decodedStrRaw) == 0) {
            wasOctalParsingNeeded = false;
        } else {
            wasOctalParsingNeeded = true;
        }

        if (decodedStrParsed != null && decodedStrParsed != "") {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(decodedStrParsed);

            // get email and user_id
            if (jsonObject.get("_p2") != null) {
                p2 = jsonObject.get("_p2").toString().toLowerCase();
                if (p2.contains("@")) {
                    jsonObject.put("user_email", p2);
                    jsonObject.put("user_email_back", p2);
                } else if (p2 != null && p2.length() > 0) {
                    jsonObject.put("user_km_id", p2);
                }
            }
            // get email and user_id
            if (jsonObject.get("_p") != null) {
                p = jsonObject.get("_p").toString().toLowerCase();
                if (p.contains("@")) {
                    jsonObject.put("user_email", p);
                    jsonObject.put("user_email_back", p);
                } else if (p != null && p.length() > 0) {
                    jsonObject.put("user_km_id", p);
                }
            }

            // Add Event
            if (jsonObject.get("_n") != null) {
                event = jsonObject.get("_n").toString();
                if (event != null) {
                    jsonObject.put("event", event);
                }
            }

            // add unix timestamp and datetime
            long currentDateTime = System.currentTimeMillis();
            Date currentDate = new Date(currentDateTime);
            if (jsonObject.get("_t") == null) {
                return (new KeyRowWrapper(jsonString, null, TRACKING_COUNTER.INVALID_JSON_ROW,
                        TRACKING_COUNTER.INVALID_DATE));
            }
            long kmTimeDateMilliSeconds;
            long kmTimeDateMilliSecondsMobile;
            try {
                tTimestampValue = (String) jsonObject.get("_t").toString();

                //See if new record with server timestamp
                if (jsonObject.get("_server_timestamp") != null) {
                    serverTimestampValue = (String) jsonObject.get("_server_timestamp").toString();
                } else {
                    serverTimestampValue = "0";
                }

                //Deal with mobile timedate cases
                if (jsonObject.get("_c") != null) {
                    if (serverTimestampValue.equals("0")) {
                        timestampValueOutput = tTimestampValue;
                        kmTimeDateMilliSecondsMobile = 0;
                    } else {
                        timestampValueOutput = serverTimestampValue;
                        mobileTimestampValueOutput = tTimestampValue;
                        jsonObject.put("km_timestamp_mobile", mobileTimestampValueOutput);
                        kmTimeDateMilliSecondsMobile = Long.parseLong(mobileTimestampValueOutput) * 1000;
                    }
                } else {//Ignore server time
                        //TODO Need a way to resolve mobile identify events
                    serverTimestampValue = "0";
                    timestampValueOutput = tTimestampValue;
                    kmTimeDateMilliSecondsMobile = 0;
                }

                jsonObject.put("km_timestamp", timestampValueOutput);
                kmTimeDateMilliSeconds = Long.parseLong(timestampValueOutput) * 1000;
            } catch (Exception e) {
                return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.INVALID_JSON_ROW,
                        TRACKING_COUNTER.INVALID_DATE));
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(kmTimeDateMilliSeconds);
            String event_timedate = dateFormatter.format(calendar.getTime());
            jsonObject.put("event_timedate", event_timedate);

            if (kmTimeDateMilliSecondsMobile > 0) {
                calendar.setTimeInMillis(kmTimeDateMilliSecondsMobile);
                String event_timedate_mobile = dateFormatter.format(calendar.getTime());
                jsonObject.put("event_timedate_mobile", event_timedate_mobile);
            }

            // add Map Reduce json_filename
            jsonObject.put("filename", fileNameInputToMapper);
            jsonString = jsonObject.toString();

            //Add bucket path
            jsonObject.put("bucket", filePath);
            jsonString = jsonObject.toString();

            // TODO add the time the record was processed by Mapper:
            //jsonObject.put("capturedDate", capturedDate);
            //jsonString = jsonObject.toString();

            return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.VALID_JSON_ROW,
                    wasOctalParsingNeeded ? null : TRACKING_COUNTER.OCTAL_PARSING_NEEDED));

        }

    } catch (Exception e) {
        // System.err.println(e.getMessage());
        // e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logger.error(errors.toString());

        logger.error("log - file " + fileNameInputToMapper);
        System.out.println("file " + fileNameInputToMapper);

        logger.error("log - row content: " + rawJsonRow.toString().replace("\t", ""));
        System.err.println("row content: " + rawJsonRow.toString().replace("\t", ""));

        System.err.println("Error skipping row");
        logger.error("Log - Error skipping row");
    }
    return null;
}

From source file:org.yccheok.jstock.charting.Utils.java

/**
 * Returns weekly chart data based on given stock history server.
 * /*from  ww  w.j a va 2 s .  c  o  m*/
 * @param stockHistoryServer the stock history server
 * @return list of weekly chart data
 */
public static List<ChartData> getWeeklyChartData(StockHistoryServer stockHistoryServer) {
    final int days = stockHistoryServer.size();
    Calendar prevCalendar = null;

    List<ChartData> chartDatas = new ArrayList<ChartData>();

    double prevPrice = 0;
    double openPrice = 0;
    double lastPrice = 0;
    double highPrice = Double.MIN_VALUE;
    double lowPrice = Double.MAX_VALUE;
    long volume = 0;
    long timestamp = 0;
    int count = 0;

    for (int i = 0; i < days; i++) {
        // First, determine the current data is same week as the previous
        // data.
        boolean isSameWeek = false;
        final long t = stockHistoryServer.getTimestamp(i);
        Stock stock = stockHistoryServer.getStock(t);

        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(t);

        if (prevCalendar != null) {
            int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
            int prevWeekOfYear = prevCalendar.get(Calendar.WEEK_OF_YEAR);
            // Is this the same week?
            isSameWeek = (weekOfYear == prevWeekOfYear);
        } else {
            // First time for us to enter this for loop.
            isSameWeek = true;
            openPrice = stock.getOpenPrice();
            prevPrice = stock.getPrevPrice();
        }

        if (isSameWeek == false) {
            // This is a new week. There must be data for previous week.
            assert (count > 0);
            ChartData chartData = ChartData.newInstance(prevPrice, openPrice, lastPrice / count, // Average last price.
                    highPrice, lowPrice, volume / count, // Average volume.
                    timestamp);
            chartDatas.add(chartData);

            // First day of the week.
            prevPrice = stock.getPrevPrice();
            openPrice = stock.getOpenPrice();
            lastPrice = stock.getLastPrice();
            highPrice = stock.getHighPrice();
            lowPrice = stock.getLowPrice();
            volume = stock.getVolume();
            timestamp = stock.getTimestamp();
            count = 1;
        } else {
            // We will not update prevPrice and openPrice. They will remain
            // as the first day of the week's.
            lastPrice += stock.getLastPrice();
            highPrice = Math.max(highPrice, stock.getHighPrice());
            lowPrice = Math.min(lowPrice, stock.getLowPrice());
            volume += stock.getVolume();
            timestamp = stock.getTimestamp();
            count++;
        }

        prevCalendar = calendar;
    }

    // Is there any data which is not being inserted yet?
    if (count > 0) {
        ChartData chartData = ChartData.newInstance(prevPrice, openPrice, lastPrice / count, highPrice,
                lowPrice, volume / count, timestamp);
        chartDatas.add(chartData);
    }

    return chartDatas;
}

From source file:org.yccheok.jstock.charting.Utils.java

/**
 * Returns monthly chart data based on given stock history server.
 *
 * @param stockHistoryServer the stock history server
 * @return list of monthly chart data//from   w w w . j  a v  a  2 s  .co m
 */
public static List<ChartData> getMonthlyChartData(StockHistoryServer stockHistoryServer) {
    final int days = stockHistoryServer.size();
    Calendar prevCalendar = null;

    List<ChartData> chartDatas = new ArrayList<ChartData>();

    double prevPrice = 0;
    double openPrice = 0;
    double lastPrice = 0;
    double highPrice = Double.MIN_VALUE;
    double lowPrice = Double.MAX_VALUE;
    long volume = 0;
    long timestamp = 0;
    int count = 0;

    for (int i = 0; i < days; i++) {
        // First, determine the current data is same month as the previous
        // data.
        boolean isSameMonth = false;
        final long t = stockHistoryServer.getTimestamp(i);
        Stock stock = stockHistoryServer.getStock(t);

        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(t);

        if (prevCalendar != null) {
            int month = calendar.get(Calendar.MONTH);
            int prevMonth = prevCalendar.get(Calendar.MONTH);
            // Is this the same month?
            isSameMonth = (month == prevMonth);
        } else {
            // First time for us to enter this for loop.
            isSameMonth = true;
            openPrice = stock.getOpenPrice();
            prevPrice = stock.getPrevPrice();
        }

        if (isSameMonth == false) {
            // This is a new month. There must be data for previous month.
            assert (count > 0);
            ChartData chartData = ChartData.newInstance(prevPrice, openPrice, lastPrice / count, // Average last price.
                    highPrice, lowPrice, volume / count, // Average volume.
                    timestamp);
            chartDatas.add(chartData);

            // First day of the month.
            prevPrice = stock.getPrevPrice();
            openPrice = stock.getOpenPrice();
            lastPrice = stock.getLastPrice();
            highPrice = stock.getHighPrice();
            lowPrice = stock.getLowPrice();
            volume = stock.getVolume();
            timestamp = stock.getTimestamp();
            count = 1;
        } else {
            // We will not update prevPrice and openPrice. They will remain
            // as the first day of the month's.
            lastPrice += stock.getLastPrice();
            highPrice = Math.max(highPrice, stock.getHighPrice());
            lowPrice = Math.min(lowPrice, stock.getLowPrice());
            volume += stock.getVolume();
            timestamp = stock.getTimestamp();
            count++;
        }

        prevCalendar = calendar;
    }

    // Is there any data which is not being inserted yet?
    if (count > 0) {
        ChartData chartData = ChartData.newInstance(prevPrice, openPrice, lastPrice / count, highPrice,
                lowPrice, volume / count, timestamp);
        chartDatas.add(chartData);
    }

    return chartDatas;
}