I'm trying to receive a string to a date. Here's an example of the string:
val date = "10/10/2016 12:00:00 AM" //format month/day/year
Now, I'd like to convert this string into a date. To do that, I'm trying to run the following:
val formatter = SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa")
var date = formatter.parse(date)
Whenever this code is running on devices running android 8, everything works out great. However, if I try to run in older devices (ex.: phones using Android 6), I end up with a ParseException:
Unparseable date: "10/10/2016 12:00:00 AM" (at offset 20)
I've noticed that removing the AM/PM characters (aa) from the string solves the parsing exception. Can someone please tell me what's going on here?
thanks
Regards,
Luis
PS: the code runs without any problem in the emulator, but not in real devices
Try this :
val date = "10/10/2016 12:00:00 AM"
val formatter = SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.US)
var date = formatter.parse(date)
Got from here : https://developer.android.com/reference/java/text/SimpleDateFormat?hl=pt-br
Looks like they never use "aa" for "PM/AM" value but rather "a" or "aaa".
Also from this response : Unable to parse DateTime-string with AM/PM marker
They recommend changing your default Locale To Locale.US if you have different symbols for PM/AM
Related
I need to parse a string from my database which has "Mon Jul 18 12:58:05 2022" string as value. Weirdly it only works with emulator. But, if i try to uses my app in my phone it throws Unparseable date error. My phone is using android 9 which use sdk 28, so i think it should be fine. I alread tried to remove the timezone which in many cases could cause the problem. But, after i remove it and the error still happen. It took me sometime to figure this out, but in the end i still got no answer. I just wanted to know what causing such problem and how to fix it?
Here is my code :
ref.child(currentData.id.toString()).child("onwork_start").get().addOnSuccessListener {
val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy")
val time = sdf.parse(it.value.toString())
val date = SimpleDateFormat("dd MMM HH:mm")
val show_time = date.format(time)
holder.tv_konfirmasi_bill.text = show_time.toString()
I have a problem in convert time coming from server and I want to convert it to 24 hour. I'm using the following code:
String timeComeFromServer = "3:30 PM";
SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a");
SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm");
try {
((TextView)findViewById(R.id.ahmad)).setText(date24Format.format(date12Format.parse(timeComeFromServer)));
} catch (ParseException e) {
e.printStackTrace();
}
There is the error:
Method threw 'java.text.ParseException' exception.)
Detailed error message is:
Unparseable date: "3:30 PM" (at offset 5)
But if I replace PM to p.m. it works without any problem like this:
timeComeFromServer = timeComeFromServer.replaceAll("PM", "p.m.").replaceAll("AM", "a.m.");
Can any one tell me which is the correct way?
SimpleDateFormat uses the system's default locale (which you can check using the java.util.Locale class, calling Locale.getDefault()). This locale is device/environment specific, so you have no control over it and can have different results in each device.
And some locales might have a different format for AM/PM field. Example:
Date d = new Date();
System.out.println(new SimpleDateFormat("a", new Locale("es", "US")).format(d));
System.out.println(new SimpleDateFormat("a", Locale.ENGLISH).format(d));
The output is:
p.m.
PM
To not depend on that, you can use Locale.ENGLISH in your formatters, so you won't depend on the system/device's default configuration:
String timeComeFromServer = "3:30 PM";
// use English Locale
SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm");
System.out.println(date24Format.format(date12Format.parse(timeComeFromServer)));
The output is:
15:30
The second formatter doesn't need a specific locale as it's not dealing with locale specific information.
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
One detail is that SimpleDateFormat always works with Date objects, which has the full timestamp (the number of milliseconds since 1970-01-01T00:00Z), and both classes implicity use the system default timezone behind the scenes, which can mislead you and generate unexpected and hard to debug results. But in this specific case, you need only the time fields (hour and minutes) and there's no need to work with timestamp values. The new API has specific classes for each case, much better and less error prone.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need ThreeTenABP (more on how to use it here).
You can use a org.threeten.bp.format.DateTimeFormatter and parse the input to a org.threeten.bp.LocalTime:
String timeComeFromServer = "3:30 PM";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime time = LocalTime.parse(timeComeFromServer, parser);
System.out.println(time.format(formatter));
The output is:
15:30
For this specific case, you could also use time.toString() to get the same result. You can refer to javadoc for more info about the backport API.
I am using
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy hh:mm a");
String dateAsString = dateFormat.format(gmt);
And getting String 06-06-2017 08:15 a.m.
Why I am getting a.m. instated of AM or PM?
The AM/PM/a.m. actually depends on the device. Try the same code on other devices and you might get to see a different result. If you need AM/PM only, then you need to do it manually by replacing the dots and converting it to uppercase.
It depends on the locale. If you use SimpleDateFormat (which you may not want to do, see below), I recommend you give it an explicit locale. The one you construct uses the device’s default, which explains why you get different results on different devices. If you want that, use new SimpleDateFormat("MM-dd-yyyy hh:mm a", Locale.getDefault()) so the reader knows you have thought about it. To make sure you get AM and PM, use for example new SimpleDateFormat("MM-dd-yyyy hh:mm a", Locale.ENGLISH).
Why would you not want to use SimpleDateFormat? I consider it long outdated since the much better replacement for the Java 1.0 and 1.1 classes came out with Java 8 in 2014. They have also been backported to Android Java 7 in the ThreeTenABP. Get this and write for example:
LocalDateTime gmt = LocalDateTime.of(2017, Month.JUNE, 6, 8, 15);
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("MM-dd-uuuu hh:mm a",
Locale.ENGLISH);
String dateAsString = gmt.format(dateTimeFormat);
The result is
06-06-2017 08:15 AM
To make explicit that the time is in GMT, you may use an OffsetDateTime with offset ZoneOffset.UTC.
Link: How to use ThreeTenABP in Android Project.
I am trying to get the present time in this format in an android app. time= "05:09pm 08/02/2011" Right now I am using Calendar c=Calendar.getInstance() and c.getTime() to get the time and its coming out as Tue Aug 23 02:34:25 PDT 2011.
Thanks
You need to use the DateFormat Class
Something like this will get you the current time in the format you desire.
DateFormat.format("hh:mmaa dd/MM/yyyy", System.currentTimeMillis());
Use a SimpleDateFormat.
Format should be like
SimpleDateFormat sdf = new SimpleDateFormat( "HH:mma dd/MM/yyyy" );
sdf.format( yourDate );
Regards,
Stéphane
There are many ways to do that in Android. You can use the SimpleDateFormat wich is a class for formatting and parsing dates. Formatting turns a Date into a String, and parsing turns a String into a Date. Or you can the class Formatter wich is low level but managing the localization is your responsibility.
You may find source code example on the Android javadoc on those classes
I have been working on problem of date format selected by users in the Android Phone.
I have gone through almost many question and answers on the stackoverlow and havent got the perfect answer.
For example:-
I have selected dateformat in phone is "Sat, 31 Dec 2011"
But when I used as based question answered on stackoverflow:-
DateFormat df = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
tv.setText(df.format(date));
Above code returns me 06/08/2011 (mm/dd/yyyy) format.
But see the date format i selected on phone. How can i get the exact format?
In an application I'm currently developing I use the following, which I believe will do what you require
final String format = Settings.System.getString(getContentResolver(), Settings.System.DATE_FORMAT);
if (TextUtils.isEmpty(format)) {
dateFormat = android.text.format.DateFormat.getMediumDateFormat(getApplicationContext());
} else {
dateFormat = new SimpleDateFormat(format);
}
The DateFormat.getDateFormat works as expected. It returns one of three possible formats:
MM/DD/YYYY
DD/MM/YYYY
YYYY/MM/DD
I'm not sure how you set your "Sat, 31 Dec 2011" format, but as far as I know stock Android allows to set only one of three mentioned formats (Settings -> Date and Time -> Select Date Format).
Try this
Date inDate = inFormat.parse(in);
DateFormat outFormat = android.text.format.DateFormat.getDateFormat(context);
out=outFormat.format(inDate);