1

This method is not working for Android Kitkat, but works in Android Oreo very well.

   public String parseDateToTime(String time) {

    String inputPattern = "dd/MM/yyyy hh:mm aa";
    String outputPattern = "hh:mm aa";
    SimpleDateFormat inputFormat = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        inputFormat = new SimpleDateFormat(inputPattern);
    }
    SimpleDateFormat outputFormat = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        outputFormat = new SimpleDateFormat(outputPattern);
    }

    Date date = null;
    String str = null;

    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            date = inputFormat.parse(time);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            str = outputFormat.format(date);
        }


    } catch (ParseException e) {
        e.printStackTrace();
    }
    Log.d("timecon",str);
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
kanaga
  • 9
  • 4
  • 1
    Make sure you have imported this **`import java.text.SimpleDateFormat;`** instead of this **`import android.icu.text.SimpleDateFormat;`** – AskNilesh Oct 12 '18 at 12:12
  • import android.icu.text.SimpleDateFormat I have use this one – kanaga Oct 12 '18 at 12:16
  • You need to use this **`import java.text.SimpleDateFormat;`** check this https://stackoverflow.com/questions/39055963/simpledateformat-gives-api-error – AskNilesh Oct 12 '18 at 12:17
  • 2
    You are always excluding KitKat. `inputFormat` and `outputFormat` are always null due to this condition `if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)` so the code will skip the try-except block – Lorenzo Vincenzi Oct 12 '18 at 12:36
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Oct 13 '18 at 05:49

2 Answers2

1

The peace of code does not execute as your version check. Because Android Kitkat is older than android N (Nougat).

Build.VERSION.SDK_INT >= Build.VERSION_CODES.N.

It will be executed only N and above OS devices.

Md. Zakir Hossain
  • 1,082
  • 11
  • 24
Ramesh Yankati
  • 1,197
  • 9
  • 13
1

in your code you used Build.VERSION_CODES.N that means Android Nougat, so when Android Kitkat is older than android N then Build.VERSION.SDK_INT >= Build.VERSION_CODES.N will not be true but because android Oreo is newer than android Nougat Build.VERSION.SDK_INT >= Build.VERSION_CODES.N will be true and your code in if block will work.

you can check this link to see android VERSION_CODES constants.

arsalanelec
  • 258
  • 3
  • 9