Example usage for java.text SimpleDateFormat setTimeZone

List of usage examples for java.text SimpleDateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text SimpleDateFormat setTimeZone.

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:com.aliyun.odps.ship.common.RecordConverterTest.java

/**
 * ?string<->record?<br/>//from   w  w w .  ja v a  2s .c  o m
 * ?BIGINT\STRING\DATETIME\BOOLEAM\BOUBLE\DECIMAL<br/>
 * <br/>
 * 1) ??string?tunnelrecord.<br/>
 * 2) ?rocord??string<br/>
 * */
@Test
public void testNormal() throws Exception {

    TableSchema rs = new TableSchema();
    rs.addColumn(new Column("i1", OdpsType.BIGINT));
    rs.addColumn(new Column("s1", OdpsType.STRING));
    rs.addColumn(new Column("d1", OdpsType.DATETIME));
    rs.addColumn(new Column("b1", OdpsType.BOOLEAN));
    rs.addColumn(new Column("doub1", OdpsType.DOUBLE));
    rs.addColumn(new Column("de1", OdpsType.DOUBLE));
    String[] l = new String[] { "1", "string", "20130925101010", "true", "2345.1209", "2345.1" };
    RecordConverter cv = new RecordConverter(rs, "NULL", "yyyyMMddHHmmss", null);
    Record r = cv.parse(toByteArray(l));
    SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmss");
    formater.setTimeZone(gmt);
    assertEquals("bigint not equal.", Long.valueOf(1), r.getBigint(0));
    assertEquals("string not equal.", "string", r.getString(1));
    assertEquals("datetime not equal.", formater.parse("20130925101010"), r.getDatetime(2));
    assertEquals("boolean not equal.", Boolean.valueOf("true"), r.getBoolean(3));
    assertEquals("double not equal.", new Double("2345.1209"), r.getDouble(4));
    //    assertEquals("decimal not equal.", new BigDecimal("2345.1"), r.getDecimal(5));

    byte[][] l1 = cv.format(r);
    for (int i = 0; i < l1.length; i++) {
        assertEquals("converter at index:" + i, l[i], new String(l1[i], "UTF-8"));
    }

}

From source file:org.jasig.schedassist.impl.caldav.CaldavEventUtilsImplTest.java

/**
 * Construct an appointment for a "group" appointment (e.g. multiple visitor3).
 * Compare with 'vevent-examples/example-group-appointment.ics'.
 * //  ww  w . j  a  v a2 s.  c  om
 * @throws InputFormatException
 * @throws IOException
 * @throws ParserException
 * @throws ParseException 
 */
@Test
public void testConstructGroupAppointment()
        throws InputFormatException, IOException, ParserException, ParseException {
    CaldavEventUtilsImpl eventUtils = new CaldavEventUtilsImpl(new NullAffiliationSourceImpl());
    eventUtils.setExplicitSetTimeZone(false);

    SimpleDateFormat dateFormat = CommonDateOperations.getDateTimeFormat();
    dateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
    Date start = dateFormat.parse("20110503-0800");
    Date end = dateFormat.parse("20110503-0900");

    AvailableBlock block = AvailableBlockBuilder.createBlock(start, end, 5);
    MockCalendarAccount ownerAccount = new MockCalendarAccount();
    ownerAccount.setDisplayName("OWNER NAME");
    ownerAccount.setEmailAddress("someone@wherever.org");
    MockScheduleOwner owner = new MockScheduleOwner(ownerAccount, 1L);
    owner.setPreference(Preferences.MEETING_PREFIX, "Group Appointment");
    owner.setPreference(Preferences.LOCATION, "123 University Building");

    MockCalendarAccount visitorAccount = new MockCalendarAccount();
    visitorAccount.setDisplayName("VISITOR NAME");
    visitorAccount.setEmailAddress("somevisitor@wherever.org");
    MockScheduleVisitor visitor = new MockScheduleVisitor(visitorAccount);
    VEvent generated = eventUtils.constructAvailableAppointment(block, owner, visitor, "Test");

    MockCalendarAccount visitorAccount2 = new MockCalendarAccount();
    visitorAccount2.setDisplayName("VISITOR TWO NAME");
    visitorAccount2.setEmailAddress("somevisitor2@wherever.org");
    generated.getProperties()
            .add(eventUtils.constructSchedulingAssistantAttendee(visitorAccount2, AppointmentRole.VISITOR));

    MockCalendarAccount visitorAccount3 = new MockCalendarAccount();
    visitorAccount3.setDisplayName("VISITOR THREE NAME");
    visitorAccount3.setEmailAddress("somevisitor3@wherever.org");
    generated.getProperties()
            .add(eventUtils.constructSchedulingAssistantAttendee(visitorAccount3, AppointmentRole.VISITOR));

    Resource example = new ClassPathResource("vevent-examples/example-group-appointment.ics");
    CalendarBuilder builder = new CalendarBuilder();
    Calendar expectedCalendar = builder.build(example.getInputStream());
    VEvent expectedEvent = (VEvent) expectedCalendar.getComponents(VEvent.VEVENT).get(0);

    Assert.assertEquals(generated.getOrganizer(), expectedEvent.getOrganizer());
    Assert.assertEquals(generated.getStartDate(), expectedEvent.getStartDate());
    Assert.assertEquals(generated.getEndDate(), expectedEvent.getEndDate());
    Assert.assertEquals(generated.getSummary(), expectedEvent.getSummary());
    Assert.assertEquals(generated.getDescription(), expectedEvent.getDescription());
    Assert.assertEquals(generated.getProperty(VisitorLimit.VISITOR_LIMIT),
            expectedEvent.getProperty(VisitorLimit.VISITOR_LIMIT));

    // verify owner and visitors have correct roles in the example
    Assert.assertTrue(eventUtils.isAttendingAsOwner(expectedEvent, ownerAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(expectedEvent, visitorAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(expectedEvent, visitorAccount2));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(expectedEvent, visitorAccount3));
    // verify owner and visitors have same roles in the generated event
    Assert.assertTrue(eventUtils.isAttendingAsOwner(generated, ownerAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(generated, visitorAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(generated, visitorAccount2));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(generated, visitorAccount3));
}

From source file:org.jasig.schedassist.impl.caldav.CaldavEventUtilsImplTest.java

@Test
public void testConstructGroupAppointmentSetTimeZone() throws Exception {
    CaldavEventUtilsImpl eventUtils = new CaldavEventUtilsImpl(new NullAffiliationSourceImpl());
    eventUtils.setExplicitSetTimeZone(true);
    eventUtils.setTimeZone("America/Chicago");
    eventUtils.afterPropertiesSet();/*from www .  j  a v a 2 s .  c o  m*/

    SimpleDateFormat dateFormat = CommonDateOperations.getDateTimeFormat();
    dateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
    Date start = dateFormat.parse("20110503-0800");
    Date end = dateFormat.parse("20110503-0900");

    AvailableBlock block = AvailableBlockBuilder.createBlock(start, end, 5);
    MockCalendarAccount ownerAccount = new MockCalendarAccount();
    ownerAccount.setDisplayName("OWNER NAME");
    ownerAccount.setEmailAddress("someone@wherever.org");
    MockScheduleOwner owner = new MockScheduleOwner(ownerAccount, 1L);
    owner.setPreference(Preferences.MEETING_PREFIX, "Group Appointment");
    owner.setPreference(Preferences.LOCATION, "123 University Building");

    MockCalendarAccount visitorAccount = new MockCalendarAccount();
    visitorAccount.setDisplayName("VISITOR NAME");
    visitorAccount.setEmailAddress("somevisitor@wherever.org");
    MockScheduleVisitor visitor = new MockScheduleVisitor(visitorAccount);
    VEvent generated = eventUtils.constructAvailableAppointment(block, owner, visitor, "Test");

    MockCalendarAccount visitorAccount2 = new MockCalendarAccount();
    visitorAccount2.setDisplayName("VISITOR TWO NAME");
    visitorAccount2.setEmailAddress("somevisitor2@wherever.org");
    generated.getProperties()
            .add(eventUtils.constructSchedulingAssistantAttendee(visitorAccount2, AppointmentRole.VISITOR));

    MockCalendarAccount visitorAccount3 = new MockCalendarAccount();
    visitorAccount3.setDisplayName("VISITOR THREE NAME");
    visitorAccount3.setEmailAddress("somevisitor3@wherever.org");
    generated.getProperties()
            .add(eventUtils.constructSchedulingAssistantAttendee(visitorAccount3, AppointmentRole.VISITOR));

    Resource example = new ClassPathResource(
            "vevent-examples/example-group-appointment-with-explicit-timezone.ics");
    CalendarBuilder builder = new CalendarBuilder();
    Calendar expectedCalendar = builder.build(example.getInputStream());
    VEvent expectedEvent = (VEvent) expectedCalendar.getComponents(VEvent.VEVENT).get(0);

    Assert.assertEquals(generated.getOrganizer(), expectedEvent.getOrganizer());
    Assert.assertEquals(generated.getStartDate(), expectedEvent.getStartDate());
    Assert.assertEquals(generated.getEndDate(), expectedEvent.getEndDate());
    Assert.assertEquals(generated.getSummary(), expectedEvent.getSummary());
    Assert.assertEquals(generated.getDescription(), expectedEvent.getDescription());
    Assert.assertEquals(generated.getProperty(VisitorLimit.VISITOR_LIMIT),
            expectedEvent.getProperty(VisitorLimit.VISITOR_LIMIT));

    // verify owner and visitors have correct roles in the example
    Assert.assertTrue(eventUtils.isAttendingAsOwner(expectedEvent, ownerAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(expectedEvent, visitorAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(expectedEvent, visitorAccount2));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(expectedEvent, visitorAccount3));
    // verify owner and visitors have same roles in the generated event
    Assert.assertTrue(eventUtils.isAttendingAsOwner(generated, ownerAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(generated, visitorAccount));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(generated, visitorAccount2));
    Assert.assertTrue(eventUtils.isAttendingAsVisitor(generated, visitorAccount3));
}

From source file:com.userhook.util.UHOperation.java

public void createSession(UserHook.UHSuccessListener listener) {

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));

    String date = format.format(new Date());

    Map<String, Object> data = new HashMap<>();
    data.put("sessions", "1");
    data.put("last_launch", date);

    updateSessionData(data, listener);/*w  w  w  .j a v a 2 s  .c o m*/

    // prefetch message templates
    fetchMessageTemplates();
}

From source file:com.clustercontrol.jobmanagement.factory.JobPlanSchedule.java

/**
 * ??/*from  w  ww .  j  a  va 2  s. c  o  m*/
 * MAX_YEAR???????????null?
 * 
 * @param calendarId
 * @return
 */
public Long getNextPlan() {
    // ??next()??????????firstFlg
    while (firstFlg || next()) {
        // ???firstFlgfalse??
        if (firstFlg) {
            firstFlg = false;
        }

        SelectCalendar select = new SelectCalendar();
        m_log.debug(year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        sdf.setTimeZone(HinemosTime.getTimeZone());
        Date date = null;
        try {
            date = sdf.parse(year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second);
        } catch (ParseException e1) {
            m_log.warn("ParseException : " + e1.getMessage(), e1);
            return null;
        }
        m_log.debug("Date : " + date);

        if (calendarId == null) {
            if (date.getTime() > startTime) {
                return date.getTime();
            }
        } else {
            CalendarInfo calInfo = null;
            try {
                calInfo = select.getCalendarFull(calendarId);
                if (calInfo.getValidTimeTo() < date.getTime()) {
                    return null;
                }
                if (CalendarUtil.isRun(calInfo, date) && isDate(year, month, day)) {
                    if (date.getTime() > startTime) {
                        return date.getTime();
                    }
                }
            } catch (CalendarNotFound e) {
                m_log.warn("getNextPlan : " + e.getClass().getName() + ", " + e.getMessage());
            } catch (InvalidRole e) {
                m_log.warn("getNextPlan : " + e.getClass().getName() + ", " + e.getMessage());
            }
        }
    }
    return null;
}

From source file:com.atinternet.tracker.TVTrackingPlugin.java

/**
 * Check if campaign is valid// w ww .j  av  a  2s .  c o  m
 *
 * @param response JSONObject
 * @return JSONObject
 * @throws JSONException
 */
private Object[] checkCampaign(JSONObject response) throws JSONException {
    // invalid data
    if (!response.toString().contains(CHANNEL)) {
        return new Object[] { TVTrackingStatusCase.noChannel, null };
    }
    // no diffusion
    else if (response.get(CHANNEL).equals(UNDEFINED)) {
        return new Object[] { TVTrackingStatusCase.channelUndefined, null };
    } else {
        if (response.get(PRIORITY).equals(UNDEFINED)) {
            response.put(PRIORITY, "1");
        }
        if (response.get(LIFETIME).equals(UNDEFINED)) {
            response.put(LIFETIME, "30");
        }

        String partnerTime = (String) response.get(TIME);
        SimpleDateFormat sdf = null;
        Date date = null;

        // UTC
        try {
            sdf = new SimpleDateFormat(UTC_DATE_FORMAT, Locale.getDefault());
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            date = sdf.parse(partnerTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (date == null || Tool.getMinutesBetweenTimes(System.currentTimeMillis(), date.getTime()) > Integer
                .parseInt(String.valueOf(tracker.getConfiguration()
                        .get(TrackerConfigurationKeys.TVTRACKING_SPOT_VALIDITY_TIME)))) {
            return new Object[] { TVTrackingStatusCase.timeError, partnerTime };
        }
    }
    return new Object[] { TVTrackingStatusCase.ok, response };
}

From source file:com.aliyun.odps.ship.common.RecordConverterTest.java

/**
 * ?pattern<br/>/*from   www .  j ava2s.  c  o  m*/
 * <br/>
 * 1 pattern??<br/>
 * 2 pattern?????<br/>
 * 3) ?<br/>
 * */
@Test
public void testDatetime() throws Exception {

    TableSchema rs = new TableSchema();
    rs.addColumn(new Column("d1", OdpsType.DATETIME));

    String[] l = new String[] { "20131010101010" };
    RecordConverter cv = new RecordConverter(rs, "NULL", "yyyyMMddHHmmss", null);
    SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmss");
    formater.setTimeZone(gmt);
    Record r = cv.parse(toByteArray(l));
    assertEquals("d1 not equal.", formater.parse("20131010101010"), r.getDatetime(0));

    byte[][] l1 = cv.format(r);
    for (int i = 0; i < l1.length; i++) {
        assertEquals("converter at index:" + i, l[i], new String(l1[i]));
    }

    l = new String[] { "20131010101010" };
    cv = new RecordConverter(rs, "NULL", "yyyyMMddHHmmss", "GMT+6");
    formater = new SimpleDateFormat("yyyyMMddHHmmss");
    formater.setTimeZone(TimeZone.getTimeZone("GMT+6"));
    r = cv.parse(toByteArray(l));
    assertEquals("d1 not equal.", formater.parse("20131010101010"), r.getDatetime(0));
    l1 = cv.format(r);
    for (int i = 0; i < l1.length; i++) {
        assertEquals("converter at index:" + i, l[i], new String(l1[i]));
    }

    try {
        String[] l2 = new String[] { "20131010101080" };
        Record r2 = cv.parse(toByteArray(l2));
        fail("need fail");
    } catch (Exception e) {
        assertTrue(e.getMessage(),
                e.getMessage().indexOf("ERROR: format error - :1, DATETIME:'20131010101080'") >= 0);
    }

    l = new String[] { "2013-09-25" };
    cv = new RecordConverter(rs, "NULL", "yyyy-MM-dd", null);
    formater = new SimpleDateFormat("yyyy-MM-dd");
    formater.setTimeZone(gmt);
    r = cv.parse(toByteArray(l));
    assertEquals("d1 not equal.", formater.parse("2013-09-25"), r.getDatetime(0));
}

From source file:com.sun.socialsite.util.UtilitiesModel.java

/**
 * Format date using SimpleDateFormat format string.
 *///from w w  w  .  j a  va  2s. co m
public String formatDate(Date d, String fmt) {
    if (d == null || fmt == null)
        return fmt;

    SimpleDateFormat format = new SimpleDateFormat(fmt);
    if (tz != null) {
        format.setTimeZone(tz);
    }
    return format.format(d);
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractSystemHealthController.java

@RequestMapping(value = ("/show_status_details"), method = RequestMethod.GET)
public String showStatusDetails(@RequestParam(value = "date", required = true) String date,
        @RequestParam(value = "serviceinstanceuuid", required = true) String serviceInstanceUUID,
        @RequestParam(value = "dateformat", required = true) String dateFormat, ModelMap map) {
    logger.debug("### showStatusDetails method starting...(GET)");
    User currentUser = getCurrentUser();
    Calendar zeroHourOfTheTargetDate = Calendar
            .getInstance(TimeZone.getTimeZone(DateTimeUtils.getTimeZone(currentUser)));
    zeroHourOfTheTargetDate.clear();/*from  ww  w . jav a 2 s.c om*/
    // IMPORTANT!!! don't zero out after setting the time zone, won't work.

    SimpleDateFormat sd = new SimpleDateFormat(dateFormat);
    sd.setTimeZone(TimeZone.getTimeZone(DateTimeUtils.getTimeZone(currentUser)));
    try {
        zeroHourOfTheTargetDate.setTime(sd.parse(date));
    } catch (ParseException e) {
        logger.error("Error found ...", e);
    }
    ServiceInstance serviceInstance = connectorConfigurationManager.getInstanceByUUID(serviceInstanceUUID);
    map.addAttribute("health",
            healthService.getSystemHealth(zeroHourOfTheTargetDate.getTime(), serviceInstance));
    map.addAttribute("notifications", healthService.listNotifications(zeroHourOfTheTargetDate.getTime(),
            DateTimeUtils.getTimeZone(currentUser), 0, 0, serviceInstance));
    map.addAttribute("date", zeroHourOfTheTargetDate.getTime());
    // TODO:FIX this. List service Insatnces if required
    logger.debug("### showStatusDetails method end");
    return "system.health.statusDetails";
}

From source file:com.persistent.cloudninja.service.impl.ProvisioningServiceImpl.java

/**
 * Assigns relying party key and addresses to the relying party.
 * /*from  w  w w  .  ja  v  a  2s .  c  om*/
 * @param relyingParty
 * @param tenantId
 * @throws Exception
 */
private void assignRelyingPartyKeyAndAddresses(RelyingParty relyingParty, String tenantId) throws Exception {
    //create relying party key
    RelyingPartyKey relyingPartyKey = new RelyingPartyKey();
    relyingPartyKey.setDisplayName("RPKey" + tenantId);
    relyingPartyKey.setType("X509Certificate");
    relyingPartyKey.setUsage("Signing");

    relyingPartyKey.setValue(getCertificateBytes(tenantId));
    relyingPartyKey.setRelyingPartyId(relyingParty.getId());
    //set start time
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String startDate = dateFormat.format(calendar.getTime());
    relyingPartyKey.setStartDate(dateFormat.parse(startDate));

    //set end time
    //The certificate is valid for 1 year.
    calendar.add(Calendar.DAY_OF_YEAR, 364);
    String endDate = dateFormat.format(calendar.getTime());
    relyingPartyKey.setEndDate(dateFormat.parse(endDate));

    relyingPartyKey.setPassword(String.format(passwordPrefix, tenantId).getBytes());
    relyingPartyKey.setIsPrimary(true);
    managementService.addEntity(relyingPartyKey);

    assignRealm(relyingParty, tenantId);
    assignReturnURL(relyingParty, tenantId);
}