Example usage for java.util Calendar AM_PM

List of usage examples for java.util Calendar AM_PM

Introduction

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

Prototype

int AM_PM

To view the source code for java.util Calendar AM_PM.

Click Source Link

Document

Field number for get and set indicating whether the HOUR is before or after noon.

Usage

From source file:com.application.utils.FastDatePrinter.java

/**
 * <p>Returns a list of Rules given a pattern.</p>
 *
 * @return a {@code List} of Rule objects
 * @throws IllegalArgumentException if pattern is invalid
 *///from  www .j a v a  2  s. c o m
protected List<Rule> parsePattern() {
    final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
    final List<Rule> rules = new ArrayList<Rule>();

    final String[] ERAs = symbols.getEras();
    final String[] months = symbols.getMonths();
    final String[] shortMonths = symbols.getShortMonths();
    final String[] weekdays = symbols.getWeekdays();
    final String[] shortWeekdays = symbols.getShortWeekdays();
    final String[] AmPmStrings = symbols.getAmPmStrings();

    final int length = mPattern.length();
    final int[] indexRef = new int[1];

    for (int i = 0; i < length; i++) {
        indexRef[0] = i;
        final String token = parseToken(mPattern, indexRef);
        i = indexRef[0];

        final int tokenLen = token.length();
        if (tokenLen == 0) {
            break;
        }

        Rule rule;
        final char c = token.charAt(0);

        switch (c) {
        case 'G': // era designator (text)
            rule = new TextField(Calendar.ERA, ERAs);
            break;
        case 'y': // year (number)
            if (tokenLen == 2) {
                rule = TwoDigitYearField.INSTANCE;
            } else {
                rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
            }
            break;
        case 'M': // month in year (text and number)
            if (tokenLen >= 4) {
                rule = new TextField(Calendar.MONTH, months);
            } else if (tokenLen == 3) {
                rule = new TextField(Calendar.MONTH, shortMonths);
            } else if (tokenLen == 2) {
                rule = TwoDigitMonthField.INSTANCE;
            } else {
                rule = UnpaddedMonthField.INSTANCE;
            }
            break;
        case 'd': // day in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
            break;
        case 'h': // hour in am/pm (number, 1..12)
            rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
            break;
        case 'H': // hour in day (number, 0..23)
            rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
            break;
        case 'm': // minute in hour (number)
            rule = selectNumberRule(Calendar.MINUTE, tokenLen);
            break;
        case 's': // second in minute (number)
            rule = selectNumberRule(Calendar.SECOND, tokenLen);
            break;
        case 'S': // millisecond (number)
            rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
            break;
        case 'E': // day in week (text)
            rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
            break;
        case 'D': // day in year (number)
            rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
            break;
        case 'F': // day of week in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
            break;
        case 'w': // week in year (number)
            rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
            break;
        case 'W': // week in month (number)
            rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
            break;
        case 'a': // am/pm marker (text)
            rule = new TextField(Calendar.AM_PM, AmPmStrings);
            break;
        case 'k': // hour in day (1..24)
            rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
            break;
        case 'K': // hour in am/pm (0..11)
            rule = selectNumberRule(Calendar.HOUR, tokenLen);
            break;
        case 'z': // time zone (text)
            if (tokenLen >= 4) {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
            } else {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
            }
            break;
        case 'Z': // time zone (value)
            if (tokenLen == 1) {
                rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
            } else {
                rule = TimeZoneNumberRule.INSTANCE_COLON;
            }
            break;
        case '\'': // literal text
            final String sub = token.substring(1);
            if (sub.length() == 1) {
                rule = new CharacterLiteral(sub.charAt(0));
            } else {
                rule = new StringLiteral(sub);
            }
            break;
        default:
            throw new IllegalArgumentException("Illegal pattern component: " + token);
        }

        rules.add(rule);
    }

    return rules;
}

From source file:it.sasabz.android.sasabus.fragments.OnlineSearchFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    this.inflater_glob = inflater;
    result = inflater.inflate(R.layout.online_search_layout, container, false);

    Date datum = new Date();
    SimpleDateFormat simple = new SimpleDateFormat("dd.MM.yyyy HH:mm");

    TextView datetime = (TextView) result.findViewById(R.id.time);
    String datetimestring = "";

    datetimestring = simple.format(datum);

    datetime.setText(datetimestring);//from   w w w  . j  a v  a  2  s  . c  o m

    Button search = (Button) result.findViewById(R.id.search);

    search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AutoCompleteTextView from = (AutoCompleteTextView) result.findViewById(R.id.from_text);
            AutoCompleteTextView to = (AutoCompleteTextView) result.findViewById(R.id.to_text);
            TextView datetime = (TextView) result.findViewById(R.id.time);

            String from_txt = getThis().getResources().getString(R.string.from_txt);

            if ((!from.getText().toString().trim().equals("")
                    || !from.getHint().toString().trim().equals(from_txt))
                    && !to.getText().toString().trim().equals("")) {
                //Intent getSelect = new Intent(getThis().getActivity(), OnlineSelectStopActivity.class);
                String fromtext = "";
                if (from.getText().toString().trim().equals(""))
                    fromtext = from.getHint().toString();
                else
                    fromtext = from.getText().toString();
                String totext = to.getText().toString();
                fromtext = "(" + fromtext.replace(" -", ")");
                totext = "(" + totext.replace(" -", ")");
                Fragment fragment = new OnlineSelectFragment(fromtext, totext, datetime.getText().toString());
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction ft = fragmentManager.beginTransaction();

                Fragment old = fragmentManager.findFragmentById(R.id.onlinefragment);
                if (old != null) {
                    ft.remove(old);
                }
                ft.add(R.id.onlinefragment, fragment);
                ft.addToBackStack(null);
                ft.commit();
                fragmentManager.executePendingTransactions();
            }
        }
    });

    datetime.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(getThis().getActivity());
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
                    .findViewById(R.id.DateTimePicker);
            TextView dt = (TextView) result.findViewById(R.id.time);
            String datetimestring = dt.getText().toString();

            SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
            Date datetime = null;
            try {
                datetime = datetimeformat.parse(datetimestring);
            } catch (Exception e) {
                ;
            }
            mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes());
            mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate());
            // Check is system is set to use 24h time (this doesn't seem to
            // work as expected though)
            final String timeS = android.provider.Settings.System.getString(
                    getThis().getActivity().getContentResolver(), android.provider.Settings.System.TIME_12_24);
            final boolean is24h = !(timeS == null || timeS.equals("12"));

            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();
                            String datetimestring = "";
                            int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH);
                            int month = mDateTimePicker.get(Calendar.MONTH) + 1;
                            int year = mDateTimePicker.get(Calendar.YEAR);
                            int hour = 0;
                            int min = 0;
                            int append = 0;
                            if (mDateTimePicker.is24HourView()) {
                                hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                            } else {
                                hour = mDateTimePicker.get(Calendar.HOUR);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                                if (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM) {
                                    append = 1;
                                } else {
                                    append = 2;
                                }
                            }
                            if (day < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (day + ".");
                            if (month < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (month + "." + year + " ");
                            if (hour < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (hour + ":");
                            if (min < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += min;

                            switch (append) {
                            case 1:
                                datetimestring += " AM";
                                break;
                            case 2:
                                datetimestring += " PM";
                                break;
                            }

                            TextView time = (TextView) result.findViewById(R.id.time);
                            time.setText(datetimestring);
                            mDateTimeDialog.dismiss();
                        }
                    });
            // Cancel the dialog when the "Cancel" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is
            // clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            mDateTimePicker.setIs24HourView(is24h);
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();
        }

    });

    ImageButton datepicker = (ImageButton) result.findViewById(R.id.datepicker);

    datepicker.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(getThis().getActivity());
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
                    .findViewById(R.id.DateTimePicker);
            TextView dt = (TextView) result.findViewById(R.id.time);
            String datetimestring = dt.getText().toString();
            SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
            Date datetime = null;
            try {
                datetime = datetimeformat.parse(datetimestring);
            } catch (Exception e) {
                ;
            }
            mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes());
            mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate());
            // Check is system is set to use 24h time (this doesn't seem to
            // work as expected though)
            final String timeS = android.provider.Settings.System.getString(
                    getThis().getActivity().getContentResolver(), android.provider.Settings.System.TIME_12_24);
            final boolean is24h = !(timeS == null || timeS.equals("12"));

            // Update demo TextViews when the "OK" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();
                            String datetimestring = "";
                            int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH);
                            int month = mDateTimePicker.get(Calendar.MONTH) + 1;
                            int year = mDateTimePicker.get(Calendar.YEAR);
                            int hour = 0;
                            int min = 0;
                            int append = 0;
                            if (mDateTimePicker.is24HourView()) {
                                hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                            } else {
                                hour = mDateTimePicker.get(Calendar.HOUR);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                                if (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM) {
                                    append = 1;
                                } else {
                                    append = 2;
                                }
                            }
                            if (day < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (day + ".");
                            if (month < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (month + "." + year + " ");
                            if (hour < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (hour + ":");
                            if (min < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += min;

                            switch (append) {
                            case 1:
                                datetimestring += " AM";
                                break;
                            case 2:
                                datetimestring += " PM";
                                break;
                            }

                            TextView time = (TextView) result.findViewById(R.id.time);
                            time.setText(datetimestring);
                            mDateTimeDialog.dismiss();
                        }
                    });
            // Cancel the dialog when the "Cancel" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is
            // clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            mDateTimePicker.setIs24HourView(is24h);
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();
        }

    });
    from = (AutoCompleteTextView) result.findViewById(R.id.from_text);
    to = (AutoCompleteTextView) result.findViewById(R.id.to_text);

    from.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            InputMethodManager mgr = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.hideSoftInputFromWindow(from.getWindowToken(), 0);
        }
    });

    to.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            InputMethodManager mgr = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.hideSoftInputFromWindow(to.getWindowToken(), 0);
        }
    });

    LocationManager locman = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE);
    Location lastloc = locman.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (MySQLiteDBAdapter.exists(this.getActivity())) {
        if (lastloc == null) {
            lastloc = locman.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (lastloc != null) {
            try {
                Palina palina = PalinaList.getPalinaGPS(lastloc);
                if (palina != null) {
                    from.setHint(palina.toString());
                }
            } catch (Exception e) {
                Log.e("HomeActivity", "Fehler bei der Location", e);
            }
        } else {
            Log.v("HomeActivity", "No location found!!");
        }
        Vector<DBObject> palinalist = PalinaList.getNameList();
        MyAutocompleteAdapter adapterfrom = new MyAutocompleteAdapter(this.getActivity(),
                android.R.layout.simple_list_item_1, palinalist);
        MyAutocompleteAdapter adapterto = new MyAutocompleteAdapter(this.getActivity(),
                android.R.layout.simple_list_item_1, palinalist);

        from.setAdapter(adapterfrom);
        to.setAdapter(adapterto);
        InputMethodManager mgr = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(from.getWindowToken(), 0);
        mgr.hideSoftInputFromWindow(to.getWindowToken(), 0);
    }
    Button favorites = (Button) result.findViewById(R.id.favorites);
    favorites.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            SelectFavoritenDialog dialog = new SelectFavoritenDialog(getThis());
            dialog.show();
        }
    });

    Button mappicker = (Button) result.findViewById(R.id.map);
    mappicker.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), MapSelectActivity.class);
            startActivityForResult(intent, REQUESTCODE_ACTIVITY);
        }
    });
    return result;
}

From source file:com.etime.ETimeActivity.java

/**
 * Converts a punch to a human readable time format
 *          "12:00 AM"/*from   ww w .j  a va 2 s.co m*/
 * @param punch Punch to convert to readable string
 * @return A string conversion of a Punch in a readable format
 */
public String punchToTimeString(Punch punch) {
    Calendar calendar = punch.getCalendar();
    int hour = getHourFromCalendar(calendar);
    int minute = calendar.get(Calendar.MINUTE);
    String minStr = (minute < 10) ? "0" + minute : "" + minute;

    return " " + hour + ":" + minStr + " " + ((calendar.get(Calendar.AM_PM) == Calendar.AM) ? "AM" : "PM");
}

From source file:gov.nih.nci.cadsr.sentinel.tool.AlertRec.java

/**
 * Return the date as a string in the form mm/dd/yyyy. The time is
 * optionally included. Time is returned in AM/PM format. The output can be
 * a simple string or formated with HTML tags.
 * /*  www  .  j  a  va  2  s  .c  o  m*/
 * @param var_
 *        The time stamp to format.
 * @param flag_
 *        true for the date and time, false for the date only.
 * @param html_
 *        true to include HTML tags, false for a simple string.
 * @return String date in String format
 */
static public String dateToString(Timestamp var_, boolean flag_, boolean html_) {
    // Be sure we have an object.
    if (var_ == null)
        return (html_) ? "<i>&lt;null&gt;</i>" : "";
    Calendar cal = Calendar.getInstance();
    cal.setTime(var_);

    // Always render in Month/Day/Year format.
    String date = (formatInt(cal.get(Calendar.MONTH) + 1)) + "/" + formatInt(cal.get(Calendar.DATE)) + "/"
            + formatInt(cal.get(Calendar.YEAR));

    // Do we include time?
    if (flag_) {
        date = date + ((html_) ? "&nbsp;" : " ");
        if (cal.get(Calendar.HOUR) == 0)
            date = date + "12";
        else
            date = date + cal.get(Calendar.HOUR);

        // Put is all together.
        date = date + ":" + formatInt(cal.get(Calendar.MINUTE)) + ":" + formatInt(cal.get(Calendar.SECOND))
                + ((html_) ? "&nbsp;" : " ") + ((cal.get(Calendar.AM_PM) == 0) ? "AM" : "PM");
    }
    return date;
}

From source file:com.owncloud.android.ui.activity.ContactsPreferenceActivity.java

public void openDate(View v) {
    String backupFolderString = getResources().getString(R.string.contacts_backup_folder)
            + OCFile.PATH_SEPARATOR;//from   ww  w  . j  av  a  2  s  .c o m
    OCFile backupFolder = getStorageManager().getFileByPath(backupFolderString);

    Vector<OCFile> backupFiles = getStorageManager().getFolderContent(backupFolder, false);

    Collections.sort(backupFiles, new Comparator<OCFile>() {
        @Override
        public int compare(OCFile o1, OCFile o2) {
            if (o1.getModificationTimestamp() == o2.getModificationTimestamp()) {
                return 0;
            }

            if (o1.getModificationTimestamp() > o2.getModificationTimestamp()) {
                return 1;
            } else {
                return -1;
            }
        }
    });

    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String backupFolderString = getResources().getString(R.string.contacts_backup_folder)
                    + OCFile.PATH_SEPARATOR;
            OCFile backupFolder = getStorageManager().getFileByPath(backupFolderString);
            Vector<OCFile> backupFiles = getStorageManager().getFolderContent(backupFolder, false);

            // find file with modification with date and time between 00:00 and 23:59
            // if more than one file exists, take oldest
            Calendar date = Calendar.getInstance();
            date.set(year, month, dayOfMonth);

            // start
            date.set(Calendar.HOUR, 0);
            date.set(Calendar.MINUTE, 0);
            date.set(Calendar.SECOND, 1);
            date.set(Calendar.MILLISECOND, 0);
            date.set(Calendar.AM_PM, Calendar.AM);
            Long start = date.getTimeInMillis();

            // end
            date.set(Calendar.HOUR, 23);
            date.set(Calendar.MINUTE, 59);
            date.set(Calendar.SECOND, 59);
            Long end = date.getTimeInMillis();

            OCFile backupToRestore = null;

            for (OCFile file : backupFiles) {
                if (start < file.getModificationTimestamp() && end > file.getModificationTimestamp()) {
                    if (backupToRestore == null) {
                        backupToRestore = file;
                    } else if (backupToRestore.getModificationTimestamp() < file.getModificationTimestamp()) {
                        backupToRestore = file;
                    }
                }
            }

            if (backupToRestore != null) {
                Fragment contactListFragment = ContactListFragment.newInstance(backupToRestore, getAccount());

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.contacts_linear_layout, contactListFragment);
                transaction.commit();
            } else {
                Toast.makeText(ContactsPreferenceActivity.this, R.string.contacts_preferences_no_file_found,
                        Toast.LENGTH_SHORT).show();
            }
        }
    };

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, dateSetListener, year, month, day);
    datePickerDialog.getDatePicker().setMaxDate(backupFiles.lastElement().getModificationTimestamp());
    datePickerDialog.getDatePicker().setMinDate(backupFiles.firstElement().getModificationTimestamp());

    datePickerDialog.show();
}

From source file:eionet.util.Util.java

/**
 * A method for calculating time difference in MILLISECONDS, between a date-time specified in input parameters and the current
 * date-time. <BR>//from w  ww .j av a2 s  .c  o m
 * This should be useful for calculating sleep time for code that has a certain schedule for execution.
 *
 * @param hour
 *            An integer from 0 to 23. If less than 0 or more than 23, then the closest next hour to current hour is taken.
 * @param date
 *            An integer from 1 to 31. If less than 1 or more than 31, then the closest next date to current date is taken.
 * @param month
 *            An integer from Calendar.JANUARY to Calendar.DECEMBER. If out of those bounds, the closest next month to current
 *            month is taken.
 * @param wday
 *            An integer from 1 to 7. If out of those bounds, the closest next weekday to weekday month is taken.
 * @param zone
 *            A String specifying the time-zone in which the calculations should be done. Please see Java documentation an
 *            allowable time-zones and formats.
 * @return Time difference in milliseconds.
 */
public static long timeDiff(int hour, int date, int month, int wday, String zone) {

    GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone(zone));
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    cal.setFirstDayOfWeek(Calendar.MONDAY);

    /*
     * here we force the hour to be one of the defualts if (hour < 0) hour = 0; if (hour > 23) hour = 23;
     */
    int cur_hour = cal.get(Calendar.HOUR);

    if (cal.get(Calendar.AM_PM) == Calendar.PM) {
        cur_hour = 12 + cur_hour;
    }

    // here we assume that every full hour is accepted
    /*
     * if (hour < 0 || hour > 23) { hour = cur_hour>=23 ? 0 : cur_hour + 1; }
     */

    if (wday >= 1 && wday <= 7) {

        int cur_wday = cal.get(Calendar.DAY_OF_WEEK);
        if (hour < 0 || hour > 23) {
            if (cur_wday != wday) {
                hour = 0;
            } else {
                hour = cur_hour >= 23 ? 0 : cur_hour + 1;
            }
        }

        int amount = wday - cur_wday;
        if (amount < 0) {
            amount = 7 + amount;
        }
        if (amount == 0 && cur_hour >= hour) {
            amount = 7;
        }
        cal.add(Calendar.DAY_OF_WEEK, amount);
    } else if (month >= Calendar.JANUARY && month <= Calendar.DECEMBER) { // do something about when every date is accepted
        if (date < 1) {
            date = 1;
        }
        if (date > 31) {
            date = 31;
        }
        int cur_month = cal.get(Calendar.MONTH);
        int amount = month - cur_month;
        if (amount < 0) {
            amount = 12 + amount;
        }
        if (amount == 0) {
            if (cal.get(Calendar.DATE) > date) {
                amount = 12;
            } else if (cal.get(Calendar.DATE) == date) {
                if (cur_hour >= hour) {
                    amount = 12;
                }
            }
        }
        // cal.set(Calendar.DATE, date);
        cal.add(Calendar.MONTH, amount);
        if (date > cal.getActualMaximum(Calendar.DATE)) {
            date = cal.getActualMaximum(Calendar.DATE);
        }
        cal.set(Calendar.DATE, date);
    } else if (date >= 1 && date <= 31) {
        int cur_date = cal.get(Calendar.DATE);
        if (cur_date > date) {
            cal.add(Calendar.MONTH, 1);
        } else if (cur_date == date) {
            if (cur_hour >= hour) {
                cal.add(Calendar.MONTH, 1);
            }
        }
        cal.set(Calendar.DATE, date);
    } else {
        if (hour < 0 || hour > 23) {
            hour = cur_hour >= 23 ? 0 : cur_hour + 1;
        }
        if (cur_hour >= hour) {
            cal.add(Calendar.DATE, 1);
        }
    }

    if (hour >= 12) {
        cal.set(Calendar.HOUR, hour - 12);
        cal.set(Calendar.AM_PM, Calendar.PM);
    } else {
        cal.set(Calendar.HOUR, hour);
        cal.set(Calendar.AM_PM, Calendar.AM);
    }

    Date nextDate = cal.getTime();
    Date currDate = new Date();

    long nextTime = cal.getTime().getTime();
    long currTime = (new Date()).getTime();

    return nextTime - currTime;
}

From source file:org.sqlite.date.FastDatePrinter.java

/**
 * <p>Returns a list of Rules given a pattern.</p>
 *
 * @return a {@code List} of Rule objects
 * @throws IllegalArgumentException if pattern is invalid
 *///from  w  w w  .j a  va 2 s  .c o  m
protected List<Rule> parsePattern() {
    final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
    final List<Rule> rules = new ArrayList<Rule>();

    final String[] ERAs = symbols.getEras();
    final String[] months = symbols.getMonths();
    final String[] shortMonths = symbols.getShortMonths();
    final String[] weekdays = symbols.getWeekdays();
    final String[] shortWeekdays = symbols.getShortWeekdays();
    final String[] AmPmStrings = symbols.getAmPmStrings();

    final int length = mPattern.length();
    final int[] indexRef = new int[1];

    for (int i = 0; i < length; i++) {
        indexRef[0] = i;
        final String token = parseToken(mPattern, indexRef);
        i = indexRef[0];

        final int tokenLen = token.length();
        if (tokenLen == 0) {
            break;
        }

        Rule rule;
        final char c = token.charAt(0);

        switch (c) {
        case 'G': // era designator (text)
            rule = new TextField(Calendar.ERA, ERAs);
            break;
        case 'y': // year (number)
            if (tokenLen == 2) {
                rule = TwoDigitYearField.INSTANCE;
            } else {
                rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
            }
            break;
        case 'M': // month in year (text and number)
            if (tokenLen >= 4) {
                rule = new TextField(Calendar.MONTH, months);
            } else if (tokenLen == 3) {
                rule = new TextField(Calendar.MONTH, shortMonths);
            } else if (tokenLen == 2) {
                rule = TwoDigitMonthField.INSTANCE;
            } else {
                rule = UnpaddedMonthField.INSTANCE;
            }
            break;
        case 'd': // day in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
            break;
        case 'h': // hour in am/pm (number, 1..12)
            rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
            break;
        case 'H': // hour in day (number, 0..23)
            rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
            break;
        case 'm': // minute in hour (number)
            rule = selectNumberRule(Calendar.MINUTE, tokenLen);
            break;
        case 's': // second in minute (number)
            rule = selectNumberRule(Calendar.SECOND, tokenLen);
            break;
        case 'S': // millisecond (number)
            rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
            break;
        case 'E': // day in week (text)
            rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
            break;
        case 'D': // day in year (number)
            rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
            break;
        case 'F': // day of week in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
            break;
        case 'w': // week in year (number)
            rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
            break;
        case 'W': // week in month (number)
            rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
            break;
        case 'a': // am/pm marker (text)
            rule = new TextField(Calendar.AM_PM, AmPmStrings);
            break;
        case 'k': // hour in day (1..24)
            rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
            break;
        case 'K': // hour in am/pm (0..11)
            rule = selectNumberRule(Calendar.HOUR, tokenLen);
            break;
        case 'X': // ISO 8601 
            rule = Iso8601_Rule.getRule(tokenLen);
            break;
        case 'z': // time zone (text)
            if (tokenLen >= 4) {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
            } else {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
            }
            break;
        case 'Z': // time zone (value)
            if (tokenLen == 1) {
                rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
            } else if (tokenLen == 2) {
                rule = TimeZoneNumberRule.INSTANCE_ISO_8601;
            } else {
                rule = TimeZoneNumberRule.INSTANCE_COLON;
            }
            break;
        case '\'': // literal text
            final String sub = token.substring(1);
            if (sub.length() == 1) {
                rule = new CharacterLiteral(sub.charAt(0));
            } else {
                rule = new StringLiteral(sub);
            }
            break;
        default:
            throw new IllegalArgumentException("Illegal pattern component: " + token);
        }

        rules.add(rule);
    }

    return rules;
}

From source file:com.etime.ETimeActivity.java

/**
 * Update the button timeToClockOut/*w ww  .j a v a2  s. c  o  m*/
 * @param eightHrPunchCalendar    A calendar object specifying the time where
 *                                the user has been punched in for exactly 8 hrs
 *                                today.
 */
private void updateTimeToClockOut(Calendar eightHrPunchCalendar) {
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("Clock out at ");

    StringBuilder clockTimeString = new StringBuilder();

    clockTimeString.append(Integer.toString(getHourFromCalendar(eightHrPunchCalendar))).append(":");

    int min = eightHrPunchCalendar.get(Calendar.MINUTE);
    if (min < 10) {
        clockTimeString.append("0");
    }
    clockTimeString.append(Integer.toString(min));

    if (eightHrPunchCalendar.get(Calendar.AM_PM) == Calendar.AM) {
        clockTimeString.append(" AM");
    } else {
        clockTimeString.append(" PM");
    }

    stringBuilder.append(clockTimeString);
    timeToClockOut.setText(stringBuilder.toString());
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDatePrinter.java

/**
 * <p>Returns a list of Rules given a pattern.</p>
 *
 * @return a {@code List} of Rule objects
 * @throws IllegalArgumentException if pattern is invalid
 *//*from   w ww . jav a2  s . co  m*/
protected List<Rule> parsePattern() {
    final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
    final List<Rule> rules = new ArrayList<>();

    final String[] ERAs = symbols.getEras();
    final String[] months = symbols.getMonths();
    final String[] shortMonths = symbols.getShortMonths();
    final String[] weekdays = symbols.getWeekdays();
    final String[] shortWeekdays = symbols.getShortWeekdays();
    final String[] AmPmStrings = symbols.getAmPmStrings();

    final int length = mPattern.length();
    final int[] indexRef = new int[1];

    for (int i = 0; i < length; i++) {
        indexRef[0] = i;
        final String token = parseToken(mPattern, indexRef);
        i = indexRef[0];

        final int tokenLen = token.length();
        if (tokenLen == 0) {
            break;
        }

        Rule rule;
        final char c = token.charAt(0);

        switch (c) {
        case 'G': // era designator (text)
            rule = new TextField(Calendar.ERA, ERAs);
            break;
        case 'y': // year (number)
        case 'Y': // week year
            if (tokenLen == 2) {
                rule = TwoDigitYearField.INSTANCE;
            } else {
                rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
            }
            if (c == 'Y') {
                rule = new WeekYear((NumberRule) rule);
            }
            break;
        case 'M': // month in year (text and number)
            if (tokenLen >= 4) {
                rule = new TextField(Calendar.MONTH, months);
            } else if (tokenLen == 3) {
                rule = new TextField(Calendar.MONTH, shortMonths);
            } else if (tokenLen == 2) {
                rule = TwoDigitMonthField.INSTANCE;
            } else {
                rule = UnpaddedMonthField.INSTANCE;
            }
            break;
        case 'd': // day in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
            break;
        case 'h': // hour in am/pm (number, 1..12)
            rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
            break;
        case 'H': // hour in day (number, 0..23)
            rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
            break;
        case 'm': // minute in hour (number)
            rule = selectNumberRule(Calendar.MINUTE, tokenLen);
            break;
        case 's': // second in minute (number)
            rule = selectNumberRule(Calendar.SECOND, tokenLen);
            break;
        case 'S': // millisecond (number)
            rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
            break;
        case 'E': // day in week (text)
            rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
            break;
        case 'u': // day in week (number)
            rule = new DayInWeekField(selectNumberRule(Calendar.DAY_OF_WEEK, tokenLen));
            break;
        case 'D': // day in year (number)
            rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
            break;
        case 'F': // day of week in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
            break;
        case 'w': // week in year (number)
            rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
            break;
        case 'W': // week in month (number)
            rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
            break;
        case 'a': // am/pm marker (text)
            rule = new TextField(Calendar.AM_PM, AmPmStrings);
            break;
        case 'k': // hour in day (1..24)
            rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
            break;
        case 'K': // hour in am/pm (0..11)
            rule = selectNumberRule(Calendar.HOUR, tokenLen);
            break;
        case 'X': // ISO 8601 
            rule = Iso8601_Rule.getRule(tokenLen);
            break;
        case 'z': // time zone (text)
            if (tokenLen >= 4) {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
            } else {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
            }
            break;
        case 'Z': // time zone (value)
            if (tokenLen == 1) {
                rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
            } else if (tokenLen == 2) {
                rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES;
            } else {
                rule = TimeZoneNumberRule.INSTANCE_COLON;
            }
            break;
        case '\'': // literal text
            final String sub = token.substring(1);
            if (sub.length() == 1) {
                rule = new CharacterLiteral(sub.charAt(0));
            } else {
                rule = new StringLiteral(sub);
            }
            break;
        default:
            throw new IllegalArgumentException("Illegal pattern component: " + token);
        }

        rules.add(rule);
    }

    return rules;
}

From source file:com.panet.imeta.job.entries.special.JobEntrySpecial.java

private long getNextMonthlyExecutionTime() {
    Calendar calendar = Calendar.getInstance();

    long nowMillis = calendar.getTimeInMillis();
    int amHour = hour;
    if (amHour > 12) {
        amHour = amHour - 12;/*from  ww w .  j a v a  2  s  . c o m*/
        calendar.set(Calendar.AM_PM, Calendar.PM);
    } else {
        calendar.set(Calendar.AM_PM, Calendar.AM);
    }
    calendar.set(Calendar.HOUR, amHour);
    calendar.set(Calendar.MINUTE, minutes);
    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    if (calendar.getTimeInMillis() <= nowMillis) {
        calendar.add(Calendar.MONTH, 1);
    }
    return calendar.getTimeInMillis() - nowMillis;
}