简体   繁体   中英

Android : How can I convert a Time with am and pm format into integer seconds

I have a value in my database with this Time format "10:40 AM" now I'm going to use it to the Alarm Manager this is my alarm manager code.

Long alertTimeCatcher = new GregorianCalendar().getTimeInMillis()+10*1000;

+10*1000 I want to change the 10 inside to the double quote with my "10:40 AM" so I'm going to convert it into integer. How am I going to do this?

Let just say I have "11:40 AM" I will convert it into integer

int Time = "11:40 AM";

This is the original code then

Long alertTimeCatcher = new GregorianCalendar().getTimeInMillis()+10*1000;

Then this is what I need

Long alertTimeCatcher = new GregorianCalendar().getTimeInMillis()+Time*1000;

So in order to trigger my alarm manager I need to convert my time into integer.

This is what I've tried so far.

try {
        Cursor c = myDB.rawQuery("SELECT * FROM " + "tblEvents", null);


        int Column2 = c.getColumnIndex("Date");
        int Column3 = c.getColumnIndex("Time");

        String[] arr = new String[0];
        // Check if our result was valid.
        ArrayList<String> list = new ArrayList<String>();
        c.moveToFirst();
        if (c != null) {
            // Loop through all Results
            do {
                String Date = c.getString(Column2);
                String Time = c.getString(Column3);
                Calendar ca = Calendar.getInstance();
                SimpleDateFormat df = new SimpleDateFormat("M/dd/yyyy");
                String formattedDate = df.format(ca.getTime());


                if (Date.equalsIgnoreCase(formattedDate)) {
                    list.add(Time);

                    Toast.makeText(getApplicationContext(), "Converter : ", Toast.LENGTH_SHORT).show();
                }
            } while (c.moveToNext());
        }
        Collections.reverse(list);
    }catch(CursorIndexOutOfBoundsException e){
        e.printStackTrace();
    }
    Long alertTimeCatcher = new GregorianCalendar().getTimeInMillis()+10*1000;

    Toast.makeText(getApplicationContext(),alertTimeCatcher.toString(),Toast.LENGTH_SHORT).show();

    Intent alertIntent = new Intent(this,AlertReceiver.class);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP,alertTimeCatcher,PendingIntent.getBroadcast(this,1,alertIntent,PendingIntent.FLAG_UPDATE_CURRENT));

You can use a SimpleDateFormat to convert the String into a Date

String myStringDate = "10:40 PM"
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
Date myDate = sdf.parse(myStringDate);

Then get time in milliseconds and replace it in your query:

Calendar calendar = Calendar.getIstance();
calendar.setTime(myDate);
int hourToSeconds = calendar.get(Calendar.HOUR_OF_DAY) * 60 * 60;
int minutesToSeconds = calendar.get(Calendar.MINUTE) * 60;

int totalSeconds = hourToSeconds + minutesToSeconds ;
Long alertTimeCatcher = new GregorianCalendar().getTimeInMillis()+ totalSeconds *1000;

quick and dirty: (+ it's a one-liner)

String timeStr = "10:40 PM";

int time = (Integer.parseInt(timeStr.substring(0, timeStr.indexOf(":"))) + (timeStr.endsWith("AM") ? 0 : 12) ) * 60 * 60 + 60 * Integer.parseInt(timeStr.substring(timeStr.indexOf(":") + 1, timeStr.indexOf(" ")));

The steps to do this are really easy:

  • Find out if it's AM or PM
  • Find out the hours and the minutes of that statement ( substring and indexOf will be helpful)
  • If it's PM add 12 to the hours
  • Multiply the hours with 60*60 to get seconds
  • Mulitply the minutes with 60 to get seconds

After that you've calculated the time-string into integer seconds


The code nicely formatted and readable will be:

boolean isPM = timeStr.endsWith("PM");
int hours = Integer.parseInt(timeStr.substring(0, timeStr.indexOf(":")));
if (isPM) hours += 12;
int minutes = Integer.parseInt(timeStr.substring(timeStr.indexOf(":") + 1, timeStr.indexOf(" ")));

You can use SimpleDateFormat

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.

String strDate = "10:40 PM"
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
Date date = simpleDateFormat.parse(strDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM