0

I am using the following code to get the current time as a String in Android.

public String getTime(){

   Date date = new Date();
   String strTimeFormat = "hh:mm a";
   DateFormat dateFormat = new SimpleDateFormat(strTimeFormat);
   String formattedTime= dateFormat.format(date);
   return formattedTime;
}

The response on few mobiles I get properly as expected but on few mobiles, I am getting dots in a.m. or p.m.

for example 08:02 p .m .

this is how I am getting the data while I am supposed to get it like 08:02 pm

my question is how to resolve this issue?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
KarmaCoding
  • 87
  • 3
  • 16
  • Maybe this has to do with the Locale. Replace dots with empty string, like: `String formattedTime= dateFormat.format(date).replace(".", "");` – forpas Jul 02 '19 at 11:04
  • i can try this , its a workaround but looking for a perfect solution. – KarmaCoding Jul 02 '19 at 11:39
  • As an aside consider not using `Date` and `SimpleDateFormat`. They are old and troublesome. Instead you may add ThreeTenABP to your project and use java.time, the modern Java date and time API. – Ole V.V. Jul 02 '19 at 13:52
  • BTW it's a locale preblem. Just specifyvthe locale that your user wants. – Ole V.V. Jul 02 '19 at 14:38
  • thanks for the reply guys. – KarmaCoding Jul 02 '19 at 19:45
  • Possible duplicate of [Java - Unparseable date](https://stackoverflow.com/questions/6154772/java-unparseable-date) – Ole V.V. Jul 08 '19 at 08:26

1 Answers1

4

Try this code. Hope it works !

private String getTimeStamp() {
            DateFormat df = new SimpleDateFormat("hh:mm:ss aaa", Locale.ENGLISH);
            return df.format(Calendar.getInstance().getTime());
        }
Yyy
  • 2,285
  • 16
  • 29