-4

I am using below way to get current time in Android as below :

String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());

and getting result as : 4:51:03 PM

Now, What if I want to get time without seconds as 4:51 PM ?

Thank you

ZaptechDev Kumar
  • 164
  • 1
  • 14
  • 3
    Did you at least google for how to format date in java? It takes less time than writing question which was already asked bazillion times – Selvin Jun 27 '17 at 11:26
  • Possible duplicate of [How to remove the SECONDS field from a DateFormat](https://stackoverflow.com/questions/17886532/how-to-remove-the-seconds-field-from-a-dateformat) – Ole V.V. Jun 27 '17 at 13:10

3 Answers3

2

You can use

 DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date())

For even more control of the format you can use SimpleDateFormat.

Henry
  • 42,982
  • 7
  • 68
  • 84
2

DateFormat.getTimeInstance(DateFormat.SHORT)

works perfectly fine here: from 20:00:00 to 20:00 and from 8:00:00 PM to 8:00 PM.

or

Date myDate=new Date(Time.getTime());
DateFormat df=new SimpleDateFormat("H:mm");
String myDateStr=df.format(myDate);
Daksh Gargas
  • 3,498
  • 2
  • 23
  • 37
0

I am using java and Persian date (you can choose your TimeZone)! Its full date and Time without Second!

and you can use it like :

 view.text = DateUtil.getPersianDateTimeShort(date, " - ")

public static String getPersianDateTimeShort(String dateStr, String separator) {
    String out = "";
    try {
      if (dateStr == null || dateStr.equals(""))
        return out;

      String date = getPersianFullDate(dateStr);
      String time = getPersianShortTime(dateStr);

      out = date + separator + time;
      return out;

    } catch (Exception e) {
      Log.e(DateUtil.class.getSimpleName() + ":getPersianDateTime", e.getClass().getName() + ": " + e.getMessage());
      return "";
    }

  }

  public static String getPersianShortTime(String dateStr) {
    return getPersianShortTime(dateStr, "HH:mm", TimeZone.getDefault());
  }
  

  public static String getPersianShortTime(String dateStr, String timeFormat, TimeZone timeZone) {
    String out;
    try {
      if (dateStr == null || dateStr.equals(""))
        return "";

      SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.ENGLISH);
      sdfDate.setTimeZone(TimeZone.getTimeZone("UTC"));
      Date date = sdfDate.parse(dateStr);
      sdfDate = new SimpleDateFormat(timeFormat, Locale.ENGLISH);
      sdfDate.setTimeZone(timeZone);
      String time = sdfDate.format(date);

      out = time;
      return out;

    } catch (Exception e) {
      Log.e(DateUtil.class.getSimpleName() + ":getPersianTime", e.getClass().getName() + ": " + e.getMessage());
      return "";
    }

  }
Sana Ebadi
  • 6,656
  • 2
  • 44
  • 44