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:org.apache.olingo.client.core.v3.PrimitiveValueTest.java

@Test
public void dateTimeOffset() throws EdmPrimitiveTypeException {
    final Calendar expected = Calendar.getInstance();
    expected.clear();//from   www .j ava  2  s.  c o m
    expected.setTimeZone(TimeZone.getTimeZone("GMT"));
    expected.set(2013, 0, 10, 2, 0, 0);
    expected.set(Calendar.MILLISECOND, 22);

    final ODataValue value = getClient().getObjectFactory().newPrimitiveValueBuilder()
            .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(expected).build();
    assertEquals(EdmPrimitiveTypeKind.DateTimeOffset, value.asPrimitive().getTypeKind());

    final Calendar asCalendar = value.asPrimitive().toCastValue(Calendar.class);
    assertEquals(expected.get(Calendar.YEAR), asCalendar.get(Calendar.YEAR));
    assertEquals(expected.get(Calendar.MONTH), asCalendar.get(Calendar.MONTH));
    assertEquals(expected.get(Calendar.DATE), asCalendar.get(Calendar.DATE));
    assertEquals(expected.get(Calendar.HOUR), asCalendar.get(Calendar.HOUR));
    assertEquals(expected.get(Calendar.MINUTE), asCalendar.get(Calendar.MINUTE));
    assertEquals(expected.get(Calendar.SECOND), asCalendar.get(Calendar.SECOND));
    assertEquals(expected.get(Calendar.MILLISECOND), asCalendar.get(Calendar.MILLISECOND));

    final Timestamp asTimestamp = value.asPrimitive().toCastValue(Timestamp.class);
    assertEquals(expected.get(Calendar.MILLISECOND), asTimestamp.getNanos() / 1000000);

    assertEquals("2013-01-10T02:00:00.022Z", value.asPrimitive().toString());

    final ODataValue parsed = getClient().getObjectFactory().newPrimitiveValueBuilder()
            .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(value.asPrimitive().toValue()).build();
    assertEquals(22, parsed.asPrimitive().toCastValue(Calendar.class).get(Calendar.MILLISECOND));
}

From source file:org.sufficientlysecure.keychain.ui.adapter.SubkeysAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView vKeyId = (TextView) view.findViewById(R.id.subkey_item_key_id);
    TextView vKeyDetails = (TextView) view.findViewById(R.id.subkey_item_details);
    TextView vKeyExpiry = (TextView) view.findViewById(R.id.subkey_item_expiry);
    ImageView vCertifyIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_certify);
    ImageView vSignIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_sign);
    ImageView vEncryptIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_encrypt);
    ImageView vAuthenticateIcon = (ImageView) view.findViewById(R.id.subkey_item_ic_authenticate);
    ImageView vEditImage = (ImageView) view.findViewById(R.id.subkey_item_edit_image);
    ImageView vStatus = (ImageView) view.findViewById(R.id.subkey_item_status);

    // not used:/*from w ww .  j  av a 2 s  .  c om*/
    ImageView deleteImage = (ImageView) view.findViewById(R.id.subkey_item_delete_button);
    deleteImage.setVisibility(View.GONE);

    long keyId = cursor.getLong(INDEX_KEY_ID);
    vKeyId.setText(KeyFormattingUtils.beautifyKeyId(keyId));

    // may be set with additional "stripped" later on
    SpannableStringBuilder algorithmStr = new SpannableStringBuilder();
    algorithmStr.append(KeyFormattingUtils.getAlgorithmInfo(context, cursor.getInt(INDEX_ALGORITHM),
            cursor.getInt(INDEX_KEY_SIZE), cursor.getString(INDEX_KEY_CURVE_OID)));

    SubkeyChange change = mSaveKeyringParcel != null ? mSaveKeyringParcel.getSubkeyChange(keyId) : null;

    if (change != null && (change.mDummyStrip || change.mMoveKeyToSecurityToken)) {
        if (change.mDummyStrip) {
            algorithmStr.append(", ");
            final SpannableString boldStripped = new SpannableString(context.getString(R.string.key_stripped));
            boldStripped.setSpan(new StyleSpan(Typeface.BOLD), 0, boldStripped.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            algorithmStr.append(boldStripped);
        }
        if (change.mMoveKeyToSecurityToken) {
            algorithmStr.append(", ");
            final SpannableString boldDivert = new SpannableString(context.getString(R.string.key_divert));
            boldDivert.setSpan(new StyleSpan(Typeface.BOLD), 0, boldDivert.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            algorithmStr.append(boldDivert);
        }
    } else {
        switch (SecretKeyType.fromNum(cursor.getInt(INDEX_HAS_SECRET))) {
        case GNU_DUMMY:
            algorithmStr.append(", ");
            algorithmStr.append(context.getString(R.string.key_stripped));
            break;
        case DIVERT_TO_CARD:
            algorithmStr.append(", ");
            algorithmStr.append(context.getString(R.string.key_divert));
            break;
        case PASSPHRASE_EMPTY:
            algorithmStr.append(", ");
            algorithmStr.append(context.getString(R.string.key_no_passphrase));
            break;
        case UNAVAILABLE:
            // don't show this on pub keys
            //algorithmStr += ", " + context.getString(R.string.key_unavailable);
            break;
        }
    }
    vKeyDetails.setText(algorithmStr, TextView.BufferType.SPANNABLE);

    boolean isMasterKey = cursor.getInt(INDEX_RANK) == 0;
    if (isMasterKey) {
        vKeyId.setTypeface(null, Typeface.BOLD);
    } else {
        vKeyId.setTypeface(null, Typeface.NORMAL);
    }

    // Set icons according to properties
    vCertifyIcon.setVisibility(cursor.getInt(INDEX_CAN_CERTIFY) != 0 ? View.VISIBLE : View.GONE);
    vEncryptIcon.setVisibility(cursor.getInt(INDEX_CAN_ENCRYPT) != 0 ? View.VISIBLE : View.GONE);
    vSignIcon.setVisibility(cursor.getInt(INDEX_CAN_SIGN) != 0 ? View.VISIBLE : View.GONE);
    vAuthenticateIcon.setVisibility(cursor.getInt(INDEX_CAN_AUTHENTICATE) != 0 ? View.VISIBLE : View.GONE);

    boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0;

    Date expiryDate = null;
    if (!cursor.isNull(INDEX_EXPIRY)) {
        expiryDate = new Date(cursor.getLong(INDEX_EXPIRY) * 1000);
    }

    // for edit key
    if (mSaveKeyringParcel != null) {
        boolean revokeThisSubkey = (mSaveKeyringParcel.mRevokeSubKeys.contains(keyId));

        if (revokeThisSubkey) {
            if (!isRevoked) {
                isRevoked = true;
            }
        }

        SaveKeyringParcel.SubkeyChange subkeyChange = mSaveKeyringParcel.getSubkeyChange(keyId);
        if (subkeyChange != null) {
            if (subkeyChange.mExpiry == null || subkeyChange.mExpiry == 0L) {
                expiryDate = null;
            } else {
                expiryDate = new Date(subkeyChange.mExpiry * 1000);
            }
        }

        vEditImage.setVisibility(View.VISIBLE);
    } else {
        vEditImage.setVisibility(View.GONE);
    }

    boolean isExpired;
    if (expiryDate != null) {
        isExpired = expiryDate.before(new Date());
        Calendar expiryCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        expiryCal.setTime(expiryDate);
        // convert from UTC to time zone of device
        expiryCal.setTimeZone(TimeZone.getDefault());

        vKeyExpiry.setText(context.getString(R.string.label_expiry) + ": "
                + DateFormat.getDateFormat(context).format(expiryCal.getTime()));
    } else {
        isExpired = false;

        vKeyExpiry.setText(context.getString(R.string.label_expiry) + ": " + context.getString(R.string.none));
    }

    // if key is expired or revoked...
    boolean isInvalid = isRevoked || isExpired;
    if (isInvalid) {
        vStatus.setVisibility(View.VISIBLE);

        vCertifyIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);
        vSignIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);
        vEncryptIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);
        vAuthenticateIcon.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                PorterDuff.Mode.SRC_IN);

        if (isRevoked) {
            vStatus.setImageResource(R.drawable.status_signature_revoked_cutout_24dp);
            vStatus.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                    PorterDuff.Mode.SRC_IN);
        } else if (isExpired) {
            vStatus.setImageResource(R.drawable.status_signature_expired_cutout_24dp);
            vStatus.setColorFilter(mContext.getResources().getColor(R.color.key_flag_gray),
                    PorterDuff.Mode.SRC_IN);
        }
    } else {
        vStatus.setVisibility(View.GONE);

        vKeyId.setTextColor(mDefaultTextColor);
        vKeyDetails.setTextColor(mDefaultTextColor);
        vKeyExpiry.setTextColor(mDefaultTextColor);

        vCertifyIcon.clearColorFilter();
        vSignIcon.clearColorFilter();
        vEncryptIcon.clearColorFilter();
        vAuthenticateIcon.clearColorFilter();
    }
    vKeyId.setEnabled(!isInvalid);
    vKeyDetails.setEnabled(!isInvalid);
    vKeyExpiry.setEnabled(!isInvalid);
}

From source file:org.kalypso.simulation.ui.calccase.ModelNature.java

private Properties createVariablesForAntLaunch(final IContainer folder) throws CoreException {
    final Properties attributes = new Properties();
    final IProject project = folder.getProject();

    final KalypsoAuthPlugin authPlugin = KalypsoAuthPlugin.getDefault();
    final IKalypsoUser currentUser = authPlugin.getCurrentUser();
    final Date now = new Date();

    final TimeZone kalypsoTimezone = KalypsoCorePlugin.getDefault().getTimeZone();

    // auf x stunden vorher runden! hngt von der Modellspec ab
    final Calendar cal = Calendar.getInstance();
    cal.setTimeZone(kalypsoTimezone);
    cal.setTime(now);//from   ww w  . j  av a  2s.c om

    attributes.setProperty("kalypso.currentTime", DatatypeConverter.printDateTime(cal)); //$NON-NLS-1$
    attributes.setProperty("kalypso.timezone", kalypsoTimezone.getID()); //$NON-NLS-1$

    // erstmal auf die letzte Stunde runden
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    // jetzt solange ganze stunden abziehen, bis der Wert ins
    // Zeitvalidierungsschema passt
    int count = 0;
    while (!validateTime(cal)) {
        cal.add(Calendar.HOUR_OF_DAY, -1);

        // nach 24h sptestens abbrechen!
        count++;
        if (count == 24)
            throw new CoreException(new Status(IStatus.ERROR, KalypsoSimulationUIPlugin.getID(),
                    Messages.getString("org.kalypso.simulation.ui.calccase.ModelNature.7") + cal)); //$NON-NLS-1$
    }

    attributes.setProperty("kalypso.startforecast", DatatypeConverter.printDateTime(cal)); //$NON-NLS-1$

    // standardzeit abziehen
    final int simDiff = new Integer(m_metadata.getProperty(META_PROP_DEFAULT_SIMHOURS, "120")).intValue(); //$NON-NLS-1$
    cal.add(Calendar.HOUR_OF_DAY, -simDiff);

    attributes.setProperty("kalypso.startsim", DatatypeConverter.printDateTime(cal)); //$NON-NLS-1$

    attributes.setProperty("kalypso.currentUser", currentUser.getUserName()); //$NON-NLS-1$

    attributes.setProperty("simulation_project_loc", project.getLocation().toPortableString()); //$NON-NLS-1$

    attributes.setProperty("calc.dir", folder.getLocation().toPortableString()); //$NON-NLS-1$
    attributes.setProperty("project.dir", project.getLocation().toPortableString()); //$NON-NLS-1$

    attributes.setProperty("calc.path", folder.getFullPath().toPortableString()); //$NON-NLS-1$
    attributes.setProperty("project.path", project.getFullPath().toPortableString()); //$NON-NLS-1$

    try {
        attributes.setProperty("calc.url", ResourceUtilities.createURL(folder).toString()); //$NON-NLS-1$
        attributes.setProperty("project.url", ResourceUtilities.createURL(project).toString()); //$NON-NLS-1$
    } catch (final MalformedURLException e) {
        // should never happen
        e.printStackTrace();
    } catch (final URIException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return attributes;
}

From source file:org.eclipsetrader.kdb.internal.core.connector.SnapshotConnector.java

protected Date getDateValue(String dateValue, String timeValue) {
    String date = stripQuotes(dateValue);
    String time = stripQuotes(timeValue);

    if (date.indexOf("N/A") != -1 && time.indexOf("N/A") != -1) {
        return null;
    }//from ww w . j a v a  2s  . c o  m

    try {
        if (date.indexOf("N/A") != -1) {
            date = dateParser.format(Calendar.getInstance(timeZone).getTime());
        }
        if (time.indexOf("N/A") != -1) {
            time = timeParser.format(Calendar.getInstance(timeZone).getTime());
        }

        Calendar c = Calendar.getInstance();
        c.setTime(dateTimeParser.parse(date + " " + time)); //$NON-NLS-1$
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.setTimeZone(TimeZone.getDefault());
        if (c.get(Calendar.YEAR) < 70) {
            c.add(Calendar.YEAR, 2000);
        }

        return c.getTime();
    } catch (ParseException e) {
        Status status = new Status(IStatus.ERROR, KdbActivator.PLUGIN_ID, 0, "Error parsing date/time values",
                e);
        KdbActivator.log(status);
    }

    return null;
}

From source file:org.eclipsetrader.yahoo.internal.core.connector.SnapshotConnector.java

protected Date getDateValue(String dateValue, String timeValue) {
    String date = stripQuotes(dateValue);
    String time = stripQuotes(timeValue);

    if (date.indexOf("N/A") != -1 && time.indexOf("N/A") != -1) {
        return null;
    }/*  w ww  .  ja v a  2s.  c  o  m*/

    try {
        if (date.indexOf("N/A") != -1) {
            date = dateParser.format(Calendar.getInstance(timeZone).getTime());
        }
        if (time.indexOf("N/A") != -1) {
            time = timeParser.format(Calendar.getInstance(timeZone).getTime());
        }

        Calendar c = Calendar.getInstance();
        c.setTime(dateTimeParser.parse(date + " " + time)); //$NON-NLS-1$
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.setTimeZone(TimeZone.getDefault());
        if (c.get(Calendar.YEAR) < 70) {
            c.add(Calendar.YEAR, 2000);
        }

        return c.getTime();
    } catch (ParseException e) {
        Status status = new Status(IStatus.ERROR, YahooActivator.PLUGIN_ID, 0, "Error parsing date/time values",
                e);
        YahooActivator.log(status);
    }

    return null;
}

From source file:com.ebay.pulsar.analytics.resources.PulsarQueryResource.java

@POST
@Path("yesterday")
@Consumes(MediaType.APPLICATION_JSON)/* w w w  .  j av a2  s .com*/
@Produces(MediaType.APPLICATION_JSON)
public Response yesterday(@Context HttpServletRequest request, CoreRequest req) {
    if (logger.isDebugEnabled()) {
        logger.debug("Yesterday API called from IP: " + request.getRemoteAddr());
    }
    req.setNamespace(RequestNameSpace.yesterday);
    req.setGranularity("fifteen_minute");

    Calendar c = Calendar.getInstance();
    c.setTimeZone(TimeZone.getTimeZone("MST"));

    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    Date end = new Date(c.getTimeInMillis());

    c.add(Calendar.DATE, -1);
    Date start = new Date(c.getTimeInMillis());

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("MST"));

    req.setStartTime(dateFormat.format(start));
    req.setEndTime(dateFormat.format(end));

    boolean trace = request.getParameter("debug") == null ? false : true;
    return processRequest(req, trace);
}

From source file:org.voidsink.anewjkuapp.fragment.CalendarFragment2.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    ArrayList<WeekViewEvent> events = mWeekViewLoader.getEvents(loader.getId());
    events.clear();/*from w  w  w.j  a  v  a  2s  . c  o  m*/

    Account mAccount = AppUtils.getAccount(getContext());
    if (mAccount != null) {
        // fetch calendar colors
        final SparseIntArray mColors = new SparseIntArray();
        ContentResolver cr = getContext().getContentResolver();
        Cursor cursor = cr.query(CalendarContractWrapper.Calendars.CONTENT_URI(), new String[] {
                CalendarContractWrapper.Calendars._ID(), CalendarContractWrapper.Calendars.CALENDAR_COLOR() },
                null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int color = cursor.getInt(1);

                double lastContrast = ColorUtils.calculateContrast(color, mWeekView.getEventTextColor());
                //Log.d(TAG, String.format("color=%d %d %d, contrast=%f", Color.red(color), Color.green(color), Color.blue(color), lastContrast));

                while (lastContrast < 1.6) {
                    float[] hsv = new float[3];

                    Color.colorToHSV(color, hsv);
                    hsv[2] = Math.max(0f, hsv[2] - 0.033f); // darken
                    color = Color.HSVToColor(hsv);

                    lastContrast = ColorUtils.calculateContrast(color, mWeekView.getEventTextColor());
                    //Log.d(TAG, String.format("new color=%d %d %d, contrast=%f", Color.red(color), Color.green(color), Color.blue(color), lastContrast));

                    if (hsv[2] == 0)
                        break;
                }

                mColors.put(cursor.getInt(0), color);
            }
            cursor.close();
        }

        if (data != null) {
            data.moveToFirst();
            data.moveToPrevious();
            while (data.moveToNext()) {

                boolean allDay = data.getInt(CalendarUtils.COLUMN_EVENT_ALL_DAY) == 1;

                Calendar startTime = Calendar.getInstance();
                if (allDay) {
                    startTime.setTimeZone(TimeZone.getTimeZone("UTC"));
                }
                startTime.setTimeInMillis(data.getLong(CalendarUtils.COLUMN_EVENT_DTSTART));

                Calendar endTime = Calendar.getInstance();
                if (allDay) {
                    endTime.setTimeZone(TimeZone.getTimeZone("UTC"));
                }
                endTime.setTimeInMillis(data.getLong(CalendarUtils.COLUMN_EVENT_DTEND));
                if (allDay && endTime.getTimeInMillis() % DateUtils.DAY_IN_MILLIS == 0) {
                    endTime.add(Calendar.MILLISECOND, -1);
                }

                WeekViewEvent event = new WeekViewEvent(data.getLong(CalendarUtils.COLUMN_EVENT_ID),
                        data.getString(CalendarUtils.COLUMN_EVENT_TITLE),
                        data.getString(CalendarUtils.COLUMN_EVENT_LOCATION), startTime, endTime, allDay);

                event.setColor(mColors.get(data.getInt(CalendarUtils.COLUMN_EVENT_CAL_ID)));

                events.add(event);
            }
        }
    }

    mWeekView.notifyDatasetChanged();
}

From source file:org.alfresco.repo.publishing.PublishingEventHelper.java

public Calendar getScheduledTime(Map<QName, Serializable> eventProperties) {
    Date time = (Date) eventProperties.get(PROP_PUBLISHING_EVENT_TIME);
    String timezone = (String) eventProperties.get(PROP_PUBLISHING_EVENT_TIME_ZONE);
    Calendar scheduledTime = Calendar.getInstance();
    scheduledTime.setTime(time);//w  ww .j  a v  a  2 s. c  o  m
    scheduledTime.setTimeZone(TimeZone.getTimeZone(timezone));
    return scheduledTime;
}

From source file:org.sufficientlysecure.keychain.ui.dialog.EditSubkeyExpiryDialogFragment.java

/**
 * Creates dialog/*from  w  ww.  j  a  va  2  s.  c om*/
 */
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Activity activity = getActivity();

    mMessenger = getArguments().getParcelable(ARG_MESSENGER);
    long creation = getArguments().getLong(ARG_CREATION);
    long expiry = getArguments().getLong(ARG_EXPIRY);

    final Calendar creationCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    creationCal.setTimeInMillis(creation * 1000);
    Calendar expiryCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    expiryCal.setTimeInMillis(expiry * 1000);

    // date picker works with default time zone, we need to convert from UTC to default timezone
    creationCal.setTimeZone(TimeZone.getDefault());
    expiryCal.setTimeZone(TimeZone.getDefault());

    // Explicitly not using DatePickerDialog here!
    // DatePickerDialog is difficult to customize and has many problems (see old git versions)
    CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder(activity);

    alert.setTitle(R.string.expiry_date_dialog_title);

    LayoutInflater inflater = activity.getLayoutInflater();
    View view = inflater.inflate(R.layout.edit_subkey_expiry_dialog, null);
    alert.setView(view);

    final CheckBox noExpiry = (CheckBox) view.findViewById(R.id.edit_subkey_expiry_no_expiry);
    final DatePicker datePicker = (DatePicker) view.findViewById(R.id.edit_subkey_expiry_date_picker);
    final TextView currentExpiry = (TextView) view.findViewById(R.id.edit_subkey_expiry_current_expiry);
    final LinearLayout expiryLayout = (LinearLayout) view.findViewById(R.id.edit_subkey_expiry_layout);

    noExpiry.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                expiryLayout.setVisibility(View.GONE);
            } else {
                expiryLayout.setVisibility(View.VISIBLE);
            }
        }
    });

    if (expiry == 0L) {
        noExpiry.setChecked(true);
        expiryLayout.setVisibility(View.GONE);

        currentExpiry.setText(R.string.btn_no_date);
    } else {
        noExpiry.setChecked(false);
        expiryLayout.setVisibility(View.VISIBLE);

        currentExpiry.setText(DateFormat.getDateFormat(getActivity()).format(expiryCal.getTime()));
    }

    // date picker works based on default time zone
    Calendar todayCal = Calendar.getInstance(TimeZone.getDefault());
    if (creationCal.after(todayCal)) {
        // NOTE: This is just for the rare cases where creation is _after_ today
        // Min Date: Creation date + 1 day

        Calendar creationCalPlusOne = (Calendar) creationCal.clone();
        creationCalPlusOne.add(Calendar.DAY_OF_YEAR, 1);
        datePicker.setMinDate(creationCalPlusOne.getTime().getTime());
        datePicker.init(creationCalPlusOne.get(Calendar.YEAR), creationCalPlusOne.get(Calendar.MONTH),
                creationCalPlusOne.get(Calendar.DAY_OF_MONTH), null);
    } else {
        // Min Date: today + 1 day

        // at least one day after creation (today)
        todayCal.add(Calendar.DAY_OF_YEAR, 1);
        datePicker.setMinDate(todayCal.getTime().getTime());
        datePicker.init(todayCal.get(Calendar.YEAR), todayCal.get(Calendar.MONTH),
                todayCal.get(Calendar.DAY_OF_MONTH), null);
    }

    alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dismiss();

            long expiry;
            if (noExpiry.isChecked()) {
                expiry = 0L;
            } else {
                Calendar selectedCal = Calendar.getInstance(TimeZone.getDefault());
                //noinspection ResourceType
                selectedCal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
                // date picker uses default time zone, we need to convert to UTC
                selectedCal.setTimeZone(TimeZone.getTimeZone("UTC"));

                long numDays = (selectedCal.getTimeInMillis() / 86400000)
                        - (creationCal.getTimeInMillis() / 86400000);
                if (numDays <= 0) {
                    Activity activity = getActivity();
                    if (activity != null) {
                        Notify.create(activity, R.string.error_expiry_past, Style.ERROR).show();
                    }
                    return;
                }
                expiry = selectedCal.getTime().getTime() / 1000;
            }

            Bundle data = new Bundle();
            data.putSerializable(MESSAGE_DATA_EXPIRY, expiry);
            sendMessageToHandler(MESSAGE_NEW_EXPIRY, data);
        }
    });

    alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dismiss();
        }
    });

    return alert.show();
}

From source file:org.ow2.aspirerfid.beg.query.MasterDataQueryClient.java

/**
 * Converts the values in a calendar object into a nicely formatted string.
 * /*ww  w  .j  a  v  a2 s.  c  o  m*/
 * @param cal
 *            with the Calendar-Date
 * @return String
 */
private String prettyStringCalendar(final Calendar cal) {
    if (cal == null) {
        return null;
    }
    // set to current timezone
    cal.setTimeZone(TimeZone.getDefault());
    return TimeParser.format(cal);
}