SimpleFormatData returning null HH: mm: ss

1

I need to get only the time entered by the user, but the method I did returns null when I try to change the format to HH:mm:ss

public static Date formataData(String data) throws Exception {
    if (data == null || data.equals(""))
        return null;
    Date date = null;
    try {
        DateFormat formatter = new SimpleDateFormat("HH:mm");
        date = (java.util.Date)formatter.parse(data);
    } catch (ParseException e) {
        throw e;
    }
    return date;
}

MainActivity.java:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText peso = (EditText) findViewById(R.id.pesotxt);
    final EditText iniciosono = (EditText) findViewById(R.id.iniciohorario);
    final EditText fimsono = (EditText) findViewById(R.id.fimhorario);


                    Date hInicioSono = null;
                    Date hFimSono = null;
                    try {
                        hInicioSono = formataData(iniciosono.getText().toString());
                        hFimSono = formataData(fimsono.getText().toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

When I call the method:

    hInicioSono = formataData(iniciosono.getText().toString());

What happens:

Iwantedthedatetocomeout23:00,butitleaves"Thu Jan 01 23:00:00 BRT 1970 ". I need to check if the current time is between inicioSono and FimSono but it will never be because the date always comes 1970.

    
asked by anonymous 25.06.2016 / 17:37

1 answer

1

One of the ways is to return a String same, since parse does not problem:

public static String formataData(String data) throws Exception {
    if (data == null || data.equals(""))
        return null;
    Date date = null;
    DateFormat formatter;
    try {
        formatter = new SimpleDateFormat("HH:mm:ss");
        date = (java.util.Date) formatter.parse(data);
    } catch (ParseException e) {
        throw e;
    }
    return formatter.format(date);
}

Running on IDEONE

Or since you just need to compare time, regardless of the date, you can use the LocalTime of package java.time of java 8:

public static LocalTime formataData(String data) throws Exception {
    if (data == null || data.equals(""))
        return null;
    LocalTime lt = LocalTime.parse(data);
    return lt;
}

See also working on IDEONE .

In order to use this last method, you would also need to change the type of your variables hInicioSono and hFimSono :

LocalTime hInicioSono;
LocalTime hFimSono;
    
25.06.2016 / 18:55