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:com.twitter.elephanttwin.util.DateUtil.java

/**
 * Convert from millis to hour id//from w  w  w. j  a  va2  s  .co m
 * @param millis input millis
 * @param tz the timezone
 * @return the hour id
 */
public static int millisFromEpochToHourId(long millis, TimeZone tz) {
    Calendar cal = Calendar.getInstance(tz);
    cal.setTimeInMillis(millis);
    return calendarToHourId(cal);
}

From source file:com.twitter.elephanttwin.util.DateUtil.java

/**
 * Timezones in mysql are wacky, this takes a timestamp
 * and returns a Calendar representation of it in UTC
 *//*from   w ww. j a  va  2  s. c o m*/
public static Calendar fromSqlTimestamp(Timestamp t) {
    if (t == null) {
        return null;
    }

    Calendar cal = getCalendarInstance();
    cal.setTimeInMillis(t.getTime());
    return cal;
}

From source file:com.twitter.elephanttwin.util.DateUtil.java

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

From source file:Main.java

/**
 * Converts an XMLGregorianCalendar to a Date.
 *
 * @param xmlDate//from   w ww.  j a  v a  2  s . c o m
 *            XMLGregorianCalendar to convert.
 * @return corresponding date object.
 */
public static Date getDate(final XMLGregorianCalendar xmlDate) {
    // TODO: is this equivalent to getDate(String) processing above??

    // start with UTC, i.e. no daylight savings time.
    TimeZone timezone = TimeZone.getTimeZone("GMT");

    // adjust timezone to match xmldate
    int offsetMinutes = xmlDate.getTimezone();
    if (offsetMinutes != DatatypeConstants.FIELD_UNDEFINED) {
        timezone.setRawOffset(
                // convert minutes to milliseconds
                offsetMinutes * 60 // seconds per minute
                        * 1000 // milliseconds per second
        );
    }

    // use calendar so parsed date will be UTC
    Calendar calendar = Calendar.getInstance(timezone);
    calendar.clear();
    calendar.set(xmlDate.getYear(),
            // xmlcalendar is 1 based, calender is 0 based
            xmlDate.getMonth() - 1, xmlDate.getDay(), xmlDate.getHour(), xmlDate.getMinute(),
            xmlDate.getSecond());
    Date date = calendar.getTime();
    int millis = xmlDate.getMillisecond();
    if (millis != DatatypeConstants.FIELD_UNDEFINED) {
        calendar.setTimeInMillis(calendar.getTimeInMillis() + millis);
    }

    return date;
}

From source file:com.glaf.core.util.DateUtils.java

public static java.util.Date toDate(long ts) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(ts);
    return calendar.getTime();
}

From source file:com.twitter.elephanttwin.util.DateUtil.java

/**
 * Convert epochMS to YYYYMMDD/*from  w  w  w .j a  va 2s. c  o  m*/
 * @param epochMs the epoch ms
 * @param tz the timezone
 * @return the output string
 */
public static String epochMsToYyyyMmDd(long epochMs, TimeZone tz) {
    if (tz == null) {
        return DATEID_TIMESTAMP_FORMATTER.print(epochMs);
    } else {
        Calendar cal = Calendar.getInstance(UTC_TIMEZONE);
        cal.setTimeInMillis(epochMs);
        SimpleDateFormat tzDateFormat = new SimpleDateFormat(DATEID_TIMESTAMP_FORMAT);
        tzDateFormat.setTimeZone(tz);
        return tzDateFormat.format(cal.getTime());
    }
}

From source file:com.appeligo.captions.CaptionListener.java

private synchronized static void checkStats() {
    int interval = 5; // minutes
    long timestamp = new Date().getTime();
    if ((timestamp - lastWrite) > (interval * 60 * 1000)) {
        lastWrite = timestamp;//www . ja  v  a  2  s.  c  o  m
        String day = Utils.getDatePath(timestamp);
        if (!day.equals(currentDay)) {
            if (statsFile != null) {
                statsFile.println("</table></body></html>");
                statsFile.close();
                statsFile = null;
            }
            currentDay = day;
        }
        if (hostname == null) {
            try {
                hostname = InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                hostname = "UnknownHost";
            }
        }
        String dirname = documentRoot + "/stats/" + currentDay + "/" + hostname;
        String statsFileName = dirname + "/searchprocstats.html";
        try {
            if (statsFile == null) {
                File dir = new File(dirname);
                if ((!dir.exists()) && (!dir.mkdirs())) {
                    throw new IOException("Error creating directory " + dirname);
                }
                File file = new File(statsFileName);
                if (file.exists()) {
                    statsFile = new PrintStream(new FileOutputStream(statsFileName, true));
                    statsFile.println("<tr><td colspan='5'>Restart</td></tr>");
                } else {
                    statsFile = new PrintStream(new FileOutputStream(statsFileName));
                    String title = "Search Process (tomcat) status for " + currentDay;
                    statsFile.println("<html><head><title>" + title + "</title></head>");
                    statsFile.println("<body><h1>" + title + "</h1>");
                    statsFile.println("<table border='1'>");
                    statsFile.println("<tr>");
                    statsFile.println("<th colspan='2'>" + interval + " Minute Intervals</th>"
                            + "<th colspan='3'>Mem Pre GC</th>" + "<th>GC</th>"
                            + "<th colspan='3'>Mem Post GC</th>");
                    statsFile.println("</tr>");
                    statsFile.println("<tr>");
                    statsFile.println("<th>Timestamp</th>");
                    statsFile.println("<th>Time</th>");
                    statsFile.println("<th>Used</th>");
                    statsFile.println("<th>Committed</th>");
                    statsFile.println("<th>Max</th>");
                    statsFile.println("<th>Millis</th>");
                    statsFile.println("<th>Used</th>");
                    statsFile.println("<th>Committed</th>");
                    statsFile.println("<th>Max</th>");
                    statsFile.println("</tr>");
                }
            }
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(TimeZone.getTimeZone("GMT"));
            cal.setTimeInMillis(timestamp);
            String time = String.format("%1$tH:%1$tM:%1$tS", cal);
            MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
            MemoryUsage memory = memoryBean.getHeapMemoryUsage();
            statsFile.print("<tr>");
            statsFile.print("<td>" + timestamp + "</td>");
            statsFile.print("<td>" + time + "</td>");
            statsFile.format("<td>%,d</td>", memory.getUsed());
            statsFile.format("<td>%,d</td>", memory.getCommitted());
            statsFile.format("<td>%,d</td>", memory.getMax());
            long beforeGC = System.currentTimeMillis();
            System.gc();
            long elapsed = System.currentTimeMillis() - beforeGC;
            statsFile.format("<td>%,d</td>", (int) elapsed);
            memoryBean = ManagementFactory.getMemoryMXBean();
            memory = memoryBean.getHeapMemoryUsage();
            statsFile.format("<td>%,d</td>", memory.getUsed());
            statsFile.format("<td>%,d</td>", memory.getCommitted());
            statsFile.format("<td>%,d</td>", memory.getMax());
            statsFile.println("</tr>");
        } catch (IOException e) {
            log.error("Error opening or writing to " + statsFileName, e);
        }
    }
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Given an alarm in hours and minutes, return a time suitable for
 * setting in AlarmManager.//w w w .  j a  va  2 s.com
 */
static Calendar calculateAlarm(int hour, int minute, Alarm.DaysOfWeek daysOfWeek) {

    // start with now
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(System.currentTimeMillis());

    int nowHour = c.get(Calendar.HOUR_OF_DAY);
    int nowMinute = c.get(Calendar.MINUTE);

    // if alarm is behind current time, advance one day
    if (hour < nowHour || hour == nowHour && minute <= nowMinute) {
        c.add(Calendar.DAY_OF_YEAR, 1);
    }
    c.set(Calendar.HOUR_OF_DAY, hour);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    int addDays = daysOfWeek.getNextAlarm(c);
    if (addDays > 0)
        c.add(Calendar.DAY_OF_WEEK, addDays);
    return c;
}

From source file:com.neuron.trafikanten.HelperFunctions.java

public static Long jsonToDate(String jsonString) {
    Calendar calendar = Calendar.getInstance();
    int indexOfPlus = jsonString.indexOf("+");
    int startOfDate = 5;
    if (jsonString.startsWith("/")) {
        // LEGACY : parse /Date( strings : Some date strings are /Date(253402297140000+0100)/, new ones are Date(253402297140000+0100)
        startOfDate = 6;/*  ww  w . j  ava2 s.com*/
        calendar.setTimeInMillis(Long.parseLong(
                jsonString.substring(startOfDate, indexOfPlus > 0 ? indexOfPlus : jsonString.length() - 2)));
    } else {
        calendar.setTimeInMillis(Long.parseLong(
                jsonString.substring(startOfDate, indexOfPlus > 0 ? indexOfPlus : jsonString.length() - 1)));
    }
    if (indexOfPlus > -1) {
        calendar.setTimeZone(
                TimeZone.getTimeZone("GMT-" + jsonString.substring(indexOfPlus, indexOfPlus + 3) + ":00"));
    }
    return calendar.getTimeInMillis();
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Sets alert in AlarmManger and StatusBar.  This is what will
 * actually launch the alert when the alarm triggers.
 *
 * @param alarm Alarm./*from   w ww . ja  v a2  s.c o  m*/
 * @param atTimeInMillis milliseconds since epoch
 */
private static void enableAlert(Context context, final Alarm alarm, final long atTimeInMillis) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (Log.LOGV) {
        Log.v("** setAlert id " + alarm.id + " atTime " + atTimeInMillis);
    }

    Intent intent = new Intent(ALARM_ALERT_ACTION);

    // XXX: This is a slight hack to avoid an exception in the remote
    // AlarmManagerService process. The AlarmManager adds extra data to
    // this Intent which causes it to inflate. Since the remote process
    // does not know about the Alarm class, it throws a
    // ClassNotFoundException.
    //
    // To avoid this, we marshall the data ourselves and then parcel a plain
    // byte[] array. The AlarmReceiver class knows to build the Alarm
    // object from the byte[] array.
    Parcel out = Parcel.obtain();
    alarm.writeToParcel(out, 0);
    out.setDataPosition(0);
    intent.putExtra(ALARM_RAW_DATA, out.marshall());

    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);

    setStatusBarIcon(context, true);

    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(atTimeInMillis);
    String timeString = formatDayAndTime(context, c);
    saveNextAlarm(context, timeString);
}