Android 12 hours Time Format getting wrong - android

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.

Related

Convert indian time zone to local time

In my app I am getting time from server in API in IST timezone, I want to show time in device's local time zone.
Below is my code for this but it seems its not working.
SimpleDateFormat serverSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat utcSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat localSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
serverSDF.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
utcSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
localSDF.setTimeZone(TimeZone.getDefault());
Date serverDate = serverSDF.parse(dateString);
String utcDate = utcSDF.format(serverDate);
Date localDate = localSDF.parse(utcDate);
From server I am getting time "2018-02-28 16:04:12" in IST and the code above displays "Wed Feb 28 10:34:12 GMT+05:30 2018".
The other answer uses GMT+05:30, but it's much better to use a proper timezone such as Asia/Kolkata. It works now because India currently uses the +05:30 offset, but it's not guaranteed to be the same forever.
If someday the government decides to change the country's offset (which already happened in the past), your code with a hardcoded GMT+05:30 will stop working - but a code with Asia/Kolkata (and a JVM with the timezone data updated) will keep working.
But today there's a better API to manipulate dates, see here how to configure it: How to use ThreeTenABP in Android Project
This is better than SimpleDateFormat, a class known to have tons of problems: https://eyalsch.wordpress.com/2009/05/29/sdf/
With this API, the code would be:
String serverDate = "2018-02-28 16:04:12";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime istLocalDate = LocalDateTime.parse(serverDate, fmt);
// set the date to India timezone
String output = istLocalDate.atZone(ZoneId.of("Asia/Kolkata"))
// convert to device's zone
.withZoneSameInstant(ZoneId.systemDefault())
// format
.format(fmt);
In my machine, the output is 2018-02-28 07:34:12 (it varies according to the default timezone of your environment).
Although it seems complicated to learn a new API, in this case I think it's totally worth it. The new API is much better, easier to use (once you learn the concepts), less error-prone, and fix lots of problems of the old API.
Check Oracle's tutorial to learn more about it: https://docs.oracle.com/javase/tutorial/datetime/
Update: Check this answer by #istt which uses modern Java8 date-time api.
You don't need to change format in UTC first. You can simply use:
SimpleDateFormat serverSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat localSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
serverSDF.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
localSDF.setTimeZone(TimeZone.getDefault());
String localDate = localSDF.format(serverSDF.parse(dateString));

Different Date Formats

I got a Problem when converting a Date in my Android App.
My Problem is that I got two different Formats of the Date.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
DateFormat formatter_date = new SimpleDateFormat("dd.MMM.yyyy");
Date myDate = null;
try {
myDate = dateFormat.parse("28.10.2015");
} catch (ParseException e) {
e.printStackTrace();
}
formatter_date.format(myDate,"dd.MM.yyyy"))
txtDate.setText(formatter_date.format(myDate,"dd.MM.yyyy")));
I want to have the date formatted as 28.Oct.2015 on a device set to English language, as 28.Okt.2015 in German, etc. So always one dot before and after the month abbreviation. When language is set to English it returns 28.Oct.2015 as it should, however, when Language is set to German it returns 28.Okt..2015 with two dots between Okt and 2015.
Is there any solution to handling this?
I should like to challenge what you are asking for. Of course you can have it, as your own answer already shows. But do you want it?
Use the built-in localized formats
Java has localized formats for all available locales (I think it’s all, in any case it’s many). I suggest you use these rather than your own idea of what a localized date should look like. While 28.Okt.2015 is probably commonplace in Austria and other German-speaking places, English-speaking people are not used to the dots in your format, and I would suspect that some people in the world will find it more or less strange.
I suggested in a comment that you add 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. Now I am taking my own medicine:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
LocalDate myDate = LocalDate.of(2015, Month.OCTOBER, 28);
System.out.println(myDate.format(dateFormatter));
Output in different locales include:
German: 28.10.2015
UK English: 28 Oct 2015
French: 28 oct. 2015
It’s not what you asked for. And you may meet objections, but that will happen no matter which format you choose because many people have their own ideas about the proper formatting for their locale. It’s pretty standardized, though, so consider it.
Edit: where did the LocalDate come from?
I understood that you were converting from a string like "28.10.2015". Converting this to a LocalDate is straightforward when you know how:
DateTimeFormatter numericDateFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu");
LocalDate myDate = LocalDate.parse("28.10.2015", numericDateFormatter);
Only if you got a java.util.Date from a legacy API that you cannot change or do not want to change just now, first thing convert it to the modern Instant type and do further conversions from there:
LocalDate myDate = oldfashionedJavaUtilDate.toInstant()
.atZone(ZoneId.of("Europe/Vienna"))
.toLocalDate();
Since this is a time zone sensitive operation, I recommend you specify an explicit time zone. You may use the JVM’s time zone setting by specifying ZoneId.systemDefault(), but be aware that this is fragile: the JVM setting may be changed under your feet by other parts of your program or other programs running in the same JVM.
What you asked for
The java.time edition of what you asked for is pretty similar to the code in your own answer:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM");
DateTimeFormatter yearFormatter = DateTimeFormatter.ofPattern("uuuu");
LocalDate myDate = LocalDate.of(2015, Month.OCTOBER, 28);
String dayOfMonth = myDate.format(dateFormatter);
String monthName = myDate.format(monthFormatter);
if (monthName.length() > 3) {
monthName = monthName.substring(0, 3);
}
String year = myDate.format(yearFormatter);
String formattedDate = dayOfMonth + '.' + monthName + '.' + year;
System.out.println(formattedDate);
Output in the same locales as above:
German: 28.Okt.2015
UK English: 28.Oct.2015
French: 28.oct.2015
There is a much shorter way to obtain the same, though:
String formattedDate = String.format("%1$td.%2$.3s.%1$tY",
myDate,
myDate.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault()));
It’s harder to read. It took me a number of attempts to get the format string %1$td.%2$.3s.%1$tY exactly right. And it will surprise those maintaining your code if they are used to DateTimeFormatter for formatting dates (and times). So I don’t really recommend it, but the choice is yours.
With another date I got the following output in French locale:
08.jui.2018
No French-speaking person, nor anyone else for that matter, will know whether this date was in June (juin) or July (juillet). In 57 of the available locales in my JVM, all 12 months of the year begin with the same three letters. Such locales include Tibetan, Swahili, Somali, Cornish, Scottish Gaelic and Vietnamese. In these languages nobody will be able to tell any months apart. Please think twice.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
SimpleDateFormat dateFormat = new SimpleDateFormat(String pattern, Locale locale);
has another constructor with Locale change Locale.ENGLISH for date to be set in English. You can check other Locale options. I generally use Locale.getDefault() to display date in user's prefered language.
Thanks for help but this solution works best for me
DateFormat formatter_month = new SimpleDateFormat("MMMM"); //Get Whole Name of Month
DateFormat formatter_day = new SimpleDateFormat("dd."); //Get Day + Dot(2 digits)
DateFormat formatter_year = new SimpleDateFormat(".yyyy"); //Get Dot + Year(4 digits)
String str_date = formatter_day.format(date)+ //Day
formatter_month.format(date).substring(0,3)+ //Month
formatter_year.format(date); //Year

Convert String in 12 (PM /AM)Hour AM PM Time to 24 Hour time android

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.

Get time of different Time zones on selection of time from time picker

I have an issue of converting selected hours and minutes to different time zones of countries.
Supposing if i select 10 am in India then i want to know at 10 am in india what will be the time in USA/New york and Tokyo.and Vice versa.
Any help is appreciable...
Thank you
please find the sollution below :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mma");
TimeZone timezone = TimeZone.getDefault();
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
Date d = new Date();
sdf.setTimeZone(timezone);
String strtime = sdf.format(d);
Log.e("str time gmt ",strtime);
sdf.setTimeZone(utcTimeZone);
strtime = sdf.format(d);
Log.e("str time utc ",strtime);
i think this will solve your problem
You can probably use Joda Time - Java date and time API. You can get the DateTimeZone depending on the Canonical ID defined in the Joda Time,
DateTimeZone zone = DateTimeZone.forID("Asia/Kolkata");
Joda Time has a complete list of Canonical ID from where you can get TimeZone depending on the Canonical ID.
So, if you want to get the local time in New York at this very moment, you would do the following
// get current moment in default time zone
DateTime dt = new DateTime();
// translate to New York local time
DateTime dtNewYork = dt.withZone(DateTimeZone.forID("America/New_York"));
For getting more idea you can refer Changing TimeZone
Try using Joda-Time library
check the org.joda.time.DateTimeZone class
Here is the API documentation for the same.
you can also get it using , Here no external API is needed
DateFormat format = new SimpleDateFormat("MMMMM d, yyyy, h:mm a");
TimeZone utc = TimeZone.getTimeZone("America/New_York");
System.out.println(utc.getID());
GregorianCalendar gc = new GregorianCalendar(utc);
Date now = gc.getTime();
System.out.println(format.format(now));
you can see more time zone on this Link
Output
America/New_York
December 29, 2012, 11:04 AM
If you don't know city name then you can also use it by Zone name as follow
DateFormat format = new SimpleDateFormat("MMMMM d, yyyy, h:mm a");
TimeZone cst = TimeZone.getTimeZone("US/Eastern");
System.out.println(cst.getID());
GregorianCalendar gc = new GregorianCalendar(cst);
Date now = gc.getTime();
format.setTimeZone(cst);
System.out.println(format.format(now))
Output
US/Eastern
December 29, 2012, 12:38 AM
Not really sure about the solution I'm going to provide but I think you can try it. GMT (Greenwich Mean Time) is a standard. I think you can keep it as a base and calculate the desired time. GMT standard is easily available too.
For example: While installing an OS like Windows XP or Windows 7, we select the time from a drop down menu. My point is, keeping this as the base, you can find the difference between the time zones in NY-US and Tokyo-Japan or vice versa as you desire it.
Hope this helps.

How do I get the time in this format in android?

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

Categories

Resources