Example usage for java.util Calendar setTimeZone

List of usage examples for java.util Calendar setTimeZone

Introduction

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

Prototype

public void setTimeZone(TimeZone value) 

Source Link

Document

Sets the time zone with the given time zone value.

Usage

From source file:de.psdev.energylogger.parser.EnergyLoggerDataParserImpl.java

@Override
public Date parseDate(final byte[] dateBytes) {
    final byte month = dateBytes[0];
    final byte day = dateBytes[1];
    final byte year = dateBytes[2];
    final byte hour = dateBytes[3];
    final byte minute = dateBytes[4];
    final Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.MONTH, month - 1);
    calendar.set(Calendar.YEAR, 2000 + year);
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

From source file:com.mercandalli.android.apps.files.user.UserModel.java

public String getAccessPassword() {
    final Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    final SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    String currentDate = dateFormatGmt.format(calendar.getTime());
    return HashUtils.sha1(HashUtils.sha1(this.password) + currentDate);
}

From source file:org.programmatori.domotica.own.sdk.config.Config.java

public Calendar getCurentTime() {
    Calendar now = GregorianCalendar.getInstance();

    Calendar ret = TimeUtility.timeAdd(timeDiff, now);
    ret.setTimeZone(timeZone);
    return ret;/*from  w  w w  .  jav  a2  s  .  com*/
}

From source file:com.appeligo.search.actions.ResponseReportAction.java

public String execute() throws Exception {
    long timestamp = new Date().getTime();
    String day = Utils.getDatePath(timestamp);
    String hostname = null;//from w w  w  .j  a v  a  2s  .  c o m
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        hostname = "UnknownHost";
    }
    String dirname = documentRoot + "/stats/" + day + "/" + hostname;
    String responseFileName = dirname + "/response-" + reporter + ".html";
    try {
        File dir = new File(dirname);
        if ((!dir.exists()) && (!dir.mkdirs())) {
            throw new IOException("Error creating directory " + dirname);
        }
        File file = new File(responseFileName);
        PrintStream responseFile = null;
        if (file.exists()) {
            responseFile = new PrintStream(new FileOutputStream(responseFileName, true));
        } else {
            responseFile = new PrintStream(new FileOutputStream(responseFileName));
            String title = "Response Times for " + getServletRequest().getServerName() + " to " + reporter;
            responseFile.println("<html><head><title>" + title + "</title></head>");
            responseFile.println("<body><h1>" + title + "</h1>");
            responseFile.println("<table border='1'>");
            responseFile.println("<tr>");
            responseFile.println("<th>Time (UTC)</th>");
            responseFile.println("<th>Response (Millis)</th>");
            responseFile.println("<th>Status</th>");
            responseFile.println("<th>Bytes Read</th>");
            responseFile.println("<th>Timed Out</th>");
            responseFile.println("<th>Exception</th>");
            responseFile.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);
        responseFile.print("<tr>");
        responseFile.print("<td>" + time + "</td>");
        responseFile.format("<td>%,d</td>", responseMillis);
        responseFile.print("<td>" + status + "</td>");
        responseFile.format("<td>%,d</td>", bytesRead);
        responseFile.print("<td>" + timedOut + "</td>");
        responseFile.print("<td>" + exception + "</td>");
        responseFile.println("</tr>");
    } catch (IOException e) {
        log.error("Error opening or writing to " + responseFileName, e);
    }

    return SUCCESS;
}

From source file:io.apiman.gateway.engine.jdbc.JdbcMetrics.java

/**
 * Process the next item in the queue.//from www  . j  a v  a2s.  c  o m
 */
@SuppressWarnings("nls")
protected void processQueue() {
    try {
        RequestMetric metric = queue.take();
        QueryRunner run = new QueryRunner(ds);

        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTime(metric.getRequestStart());

        long rstart = cal.getTimeInMillis();
        long rend = metric.getRequestEnd().getTime();
        long duration = metric.getRequestDuration();
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        long minute = cal.getTimeInMillis();
        cal.set(Calendar.MINUTE, 0);
        long hour = cal.getTimeInMillis();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        long day = cal.getTimeInMillis();
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        long week = cal.getTimeInMillis();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        long month = cal.getTimeInMillis();
        String api_org_id = metric.getApiOrgId();
        String api_id = metric.getApiId();
        String api_version = metric.getApiVersion();
        String client_org_id = metric.getClientOrgId();
        String client_id = metric.getClientId();
        String client_version = metric.getClientVersion();
        String plan = metric.getPlanId();
        String user_id = metric.getUser();
        String rtype = null;
        if (metric.isFailure()) {
            rtype = "failure";
        } else if (metric.isError()) {
            rtype = "error";
        }
        long bytes_up = metric.getBytesUploaded();
        long bytes_down = metric.getBytesDownloaded();

        // Now insert a row for the metric.
        run.update("INSERT INTO gw_requests (" + "rstart, rend, duration, month, week, day, hour, minute, "
                + "api_org_id, api_id, api_version, " + "client_org_id, client_id, client_version, plan, "
                + "user_id, resp_type, bytes_up, bytes_down) VALUES (" + "?, ?, ?, ?, ?, ?, ?, ?," + "?, ?, ?,"
                + "?, ?, ?, ?," + "?, ?, ?, ?)", rstart, rend, duration, month, week, day, hour, minute,
                api_org_id, api_id, api_version, client_org_id, client_id, client_version, plan, user_id, rtype,
                bytes_up, bytes_down);
    } catch (InterruptedException ie) {
        // This means that the thread was stopped.
    } catch (Exception e) {
        // TODO better logging of this unlikely error
        System.err.println("Error adding metric to database:"); //$NON-NLS-1$
        e.printStackTrace();
        return;
    }
}

From source file:org.openmeetings.app.remote.InvitationService.java

/**
 * send an invitation to another user by Mail
 * //from   w  w w.j  a v a2s.c o  m
 * @param SID
 * @param username
 * @param message
 * @param baseurl
 * @param email
 * @param subject
 * @param room_id
 * @param conferencedomain
 * @param isPasswordProtected
 * @param invitationpass
 * @param valid
 * @param validFromDate
 * @param validFromTime
 * @param validToDate
 * @param validToTime
 * @param language_id
  * @param jNameTimeZone
 * @return
 */
public String sendInvitationHash(String SID, String username, String message, String baseurl, String email,
        String subject, Long room_id, String conferencedomain, Boolean isPasswordProtected,
        String invitationpass, Integer valid, Date validFromDate, String validFromTime, Date validToDate,
        String validToTime, Long language_id, String jNameTimeZone) {

    try {
        log.debug("sendInvitationHash: ");

        Integer validFromHour = Integer.valueOf(validFromTime.substring(0, 2)).intValue();
        Integer validFromMinute = Integer.valueOf(validFromTime.substring(3, 5)).intValue();

        Integer validToHour = Integer.valueOf(validToTime.substring(0, 2)).intValue();
        Integer validToMinute = Integer.valueOf(validToTime.substring(3, 5)).intValue();

        log.info("validFromHour: " + validFromHour);
        log.info("validFromMinute: " + validFromMinute);

        Calendar calFrom = Calendar.getInstance();
        calFrom.setTime(validFromDate);
        calFrom.set(Calendar.HOUR_OF_DAY, validFromHour);
        calFrom.set(Calendar.MINUTE, validFromMinute);
        calFrom.set(Calendar.SECOND, 0);

        Calendar calTo = Calendar.getInstance();
        calTo.setTime(validToDate);
        calTo.set(Calendar.HOUR_OF_DAY, validToHour);
        calTo.set(Calendar.MINUTE, validToMinute);
        calTo.set(Calendar.SECOND, 0);

        Date dFrom = calFrom.getTime();
        Date dTo = calTo.getTime();

        Long users_id = sessionManagement.checkSession(SID);
        Long user_level = userManagement.getUserLevelByID(users_id);

        OmTimeZone omTimeZone = omTimeZoneDaoImpl.getOmTimeZone(jNameTimeZone);

        // If everything fails
        if (omTimeZone == null) {
            Configuration conf = cfgManagement.getConfKey(3L, "default.timezone");
            if (conf != null) {
                jNameTimeZone = conf.getConf_value();
            }
            omTimeZone = omTimeZoneDaoImpl.getOmTimeZone(jNameTimeZone);
        }

        String timeZoneName = omTimeZone.getIcal();

        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone(timeZoneName));
        int offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET);

        log.debug("addAppointment offset :: " + offset);

        Date gmtTimeStart = new Date(dFrom.getTime() - offset);
        Date gmtTimeEnd = new Date(dTo.getTime() - offset);

        Invitations invitation = invitationManagement.addInvitationLink(user_level, username, message, baseurl,
                email, subject, room_id, conferencedomain, isPasswordProtected, invitationpass, valid, dFrom,
                dTo, users_id, baseurl, language_id, true, gmtTimeStart, gmtTimeEnd, null, username);

        if (invitation != null) {
            return "success";
        } else {
            return "Sys - Error";
        }
    } catch (Exception err) {
        log.error("[sendInvitationHash]", err);
    }

    return null;

    // return
    // invitationManagement.sendInvitionLink(user_level,
    // username, message, domain, room, roomtype, baseurl, email, subject,
    // room_id);
}

From source file:ca.etsmtl.applets.etsmobile.NewsListActivity.java

private void setAlarm() {
    final Intent toAlarm = new Intent(this, NewsAlarmReceiver.class);
    final PendingIntent toDownload = PendingIntent.getBroadcast(this, 0, toAlarm,
            PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    final Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));

    updateTime.set(Calendar.HOUR_OF_DAY, 6);
    updateTime.set(Calendar.MINUTE, 00);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);/*from  w  w  w  .ja v  a2s .  c  o  m*/

    updateTime.set(Calendar.HOUR_OF_DAY, 12);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);

    updateTime.set(Calendar.HOUR_OF_DAY, 18);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);
}

From source file:com.lloydtorres.stately.helpers.SparkleHelper.java

/**
 * Calculates the remaining time for a WA resolution in human-readable form.
 * @param c App context//from  w  ww  .  ja  v  a2  s.  co  m
 * @param hoursElapsed Number of hours passed since voting started
 * @return Time remaining in human-readable form
 */
public static String calculateResolutionEnd(Context c, int hoursElapsed) {
    Calendar cal = new GregorianCalendar();
    cal.setTimeZone(TIMEZONE_TORONTO);

    // Round up to nearest hour
    if (cal.get(Calendar.MINUTE) >= 1) {
        cal.add(Calendar.HOUR, 1);
    }
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);

    cal.add(Calendar.HOUR, WA_RESOLUTION_DURATION - hoursElapsed);

    Date d = cal.getTime();
    return getReadableDateFromUTC(c, d.getTime() / 1000L);
}

From source file:org.eredlab.g4.ccl.net.ftp.parser.FTPTimestampParserImpl.java

/** 
 * Implements the one {@link  FTPTimestampParser#parseTimestamp(String)  method}
 * in the {@link  FTPTimestampParser  FTPTimestampParser} interface 
 * according to this algorithm://w ww . j  a va 2s .  c  om
 * 
 * If the recentDateFormat member has been defined, try to parse the 
 * supplied string with that.  If that parse fails, or if the recentDateFormat
 * member has not been defined, attempt to parse with the defaultDateFormat
 * member.  If that fails, throw a ParseException. 
 * 
 * @see org.apache.commons.net.ftp.parser.FTPTimestampParser#parseTimestamp(java.lang.String)    
 */
/* (non-Javadoc)
 * 
 */
public Calendar parseTimestamp(String timestampStr) throws ParseException {
    Calendar now = Calendar.getInstance();
    now.setTimeZone(this.getServerTimeZone());

    Calendar working = Calendar.getInstance();
    working.setTimeZone(this.getServerTimeZone());
    ParsePosition pp = new ParsePosition(0);

    Date parsed = null;
    if (this.recentDateFormat != null) {
        parsed = recentDateFormat.parse(timestampStr, pp);
    }
    if (parsed != null && pp.getIndex() == timestampStr.length()) {
        working.setTime(parsed);
        working.set(Calendar.YEAR, now.get(Calendar.YEAR));
        if (working.after(now)) {
            working.add(Calendar.YEAR, -1);
        }
    } else {
        pp = new ParsePosition(0);
        parsed = defaultDateFormat.parse(timestampStr, pp);
        // note, length checks are mandatory for us since
        // SimpleDateFormat methods will succeed if less than
        // full string is matched.  They will also accept, 
        // despite "leniency" setting, a two-digit number as
        // a valid year (e.g. 22:04 will parse as 22 A.D.) 
        // so could mistakenly confuse an hour with a year, 
        // if we don't insist on full length parsing.
        if (parsed != null && pp.getIndex() == timestampStr.length()) {
            working.setTime(parsed);
        } else {
            throw new ParseException("Timestamp could not be parsed with older or recent DateFormat",
                    pp.getIndex());
        }
    }
    return working;
}

From source file:org.openhab.persistence.dynamodb.internal.AbstractDynamoDBItemSerializationTest.java

@Test
public void testDateTimeTypeLocalWithStringItem() throws IOException {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT+03:00"));
    calendar.setTimeInMillis(1468773487050L); // GMT: Sun, 17 Jul 2016 16:38:07.050 GMT
    DynamoDBItem<?> dbitem = testStateGeneric(new DateTimeType(calendar), "2016-07-17T16:38:07.050Z");
    testAsHistoricGeneric(dbitem, new StringItem("foo"), new StringType("2016-07-17T16:38:07.050Z"));
}