简体   繁体   中英

How can I convert a “String HH:MM” to a “int hour HH” and “int minute MM”

I have this code. And I need convert a string "horaTarefa HH:MM" to int "hour = HH" and int "minute = MM"

I guess can I do the same thing with "dateTarefa DD/MM/YYYY" ?

SQLiteDatabase db;
db = openOrCreateDatabase("AgendadorTarefas.db",SQLiteDatabase.CREATE_IF_NECESSARY,null); { }

Cursor c = db.query("Tarefa", new String[] {
              "codTarefa", "dateTarefa", "horaTarefa", "textoTarefa"}, 
            null, null, null, null, null);

c.moveToFirst();

final ArrayList<String> result = new ArrayList<String>();

while(c.moveToNext())
{ 
    String Date = c.getString(1);
    String Hora = c.getString(2);
    String Texto = c.getString(3);
    result.add(Data + " às " + Hora + " \n" + Texto);
}

hour = Calendar.HOUR;
minute = Calendar.MINUTE;

c.close();    

It's better to use a dateformatter instead of just parsing integers. This way you have much more control over what the time and date can look like (are one-digit numbers written as 05 or 5 ? Is the time 12-hour or 24-hour format? ...)

A simple code to parse a time could look like:

try
{
    SimpleDateFormat format = new SimpleDateFormat("H:m");
    Date date = format.parse("15:34");
    int hours = date.getHours(); 
    int min   = date.getMinutes();
}
catch (ParseException e)
{
    // parsing failed
}

For a reference of what the format parameters can look like take a look at the SimpleDateFormat Documentation

If you really want to make your application international, you should also consider using Calendar instead of just Date as I did in the example.

If you know the position of the hour/minute/etc and it is always the same, you can get it with substring , and then convert it to numbers with Integer.parseInt

String Hora = "12:34";
int hour = Integer.parseInt(Hora.substring(0, 2));
int minute = Integer.parseInt(Hora.substring(3));

String Date = "12/34/5678";
int day = Integer.parseInt(Date.substring(0, 2));
int month = Integer.parseInt(Date.substring(3, 5));
int year = Integer.parseInt(Date.substring(6));

date.getHours() is deprecated so i choose to updated answer for this question by using Calendar and best answer of this question.

public static int getHour(String hourString) {
    SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.US);
    try {
        Date date = format.parse(hourString);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.HOUR_OF_DAY);
    } catch (ParseException e) {
        return Integer.parseInt(hourString.substring(0, 2));
    }
}

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