How to obtain user date time settings in android - android

I have a Calendar object, and i know how to format it using android.text.format()
How can i get the phone settings for date and time to format the object to format set by the user. Like 24 hour clock , mmm dd yyyy...

What I wanted was to provide the date and time formatted according to the user's preferences and locale, in separate TextViews.
I have done this using static methods in the DateFormat class:
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext()); // Gets system date format
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext()); // Gets system time format
txt1.setText(dateFormat.format(CalendarInstance.getTime())); // format() Returns a string according to the user's preferences (12-hr vs 24-hr) and locale
txt2.setText(timeFormat.format(CalendarInstance.getTime()));

Well, not exactly all the settings (such as 24 vs 12 hour format) selected by the user, but to use the configured locale you can use the DateUtils class.

Related

Getting 4 hours difference while getting while converting data in to device timezone?

I am getting the 4 hours difference on time zone from below lines of code on my device:
I am getting the time in such a way like 2018-09-30T13:45:00Z
My start and End Date is as follow: -
"start_date":"2017-09-13T12:15:00Z",
"end_date":"2018-09-30T13:45:00Z",
Calendar c = Calendar.getInstance(Locale.getDefault());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date localStartDate = formatter.parse(startTime);
Date localEndDate = formatter.parse(endTime);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm");
dateFormatter.setTimeZone(c.getTimeZone());
localStartDate = dateFormatter.parse(startTime);
localEndDate = dateFormatter.parse(endTime);
SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
monthFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String monthName = monthFormat.format(localStartDate);
eventDate.setMonth(monthName);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
dateFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String dateName = dateFormat.format(localStartDate);
eventDate.setDate(dateName);
SimpleDateFormat dayNameFormat = new SimpleDateFormat("EEEE");
dayNameFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String dayName1 = dayNameFormat.format(localStartDate);
String dayName2 = dayNameFormat.format(localEndDate);
eventDate.setDayName1(dayName1);
eventDate.setDayName2(dayName2);
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");
timeFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String startTimeName = timeFormat.format(localStartDate);
String endTimeName = timeFormat.format(localEndDate);
System.out.println("My Start date and end date==>>>"+startTimeName+" " +endTimeName );
Problem: Getting the 4 hours difference from above code, as I am setting my time zone to BOSTON(US), getting error.
My result from the below #Hugo solution is as below
And i am expecting the result as below
Please check it once..I have also set the TimeZone of Eastern DayLight Time but not getting proper solution..please check it once..And let me know
SimpleDateFormat and Calendar uses the JVM default timezone (unless you set a different one on them), and the default timezone can be different in each device/machine/environment. Not only that, this default can be changed without notice, even at runtime, so it's better to always make it explicit which one you're using.
When you do things like:
Calendar c = Calendar.getInstance(Locale.getDefault());
dateFormatter.setTimeZone(c.getTimeZone());
monthFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
The Calendar is created with the default timezone, so dateFormatter will also have the same zone. So does monthFormat, and also the other formatters you created. The only formatter set to a different zone is the first one (which is set to UTC).
Also, the second formatter is redundant (it does the same thing that the first one is already doing: parsing the String to a Date), so you can remove it.
Assuming that your input is a String with the value 2018-09-30T13:45:00Z: the Z in the end indicates that this date is in UTC. So you should parse it using a formatter set to UTC. So, instead of using c.getTimeZone() and TimeZone.getDefault(), you should use only TimeZone.getTimeZone("UTC").
For the output, you must set the formatters with the timezone you want to convert to. If the timezone is "EDT", set to it (but don't use exactly "EDT", see below). If you want to use the JVM default, use TimeZone.getDefault() - just check this value before, to make sure the default is what you need.
Just keep in mind that short names like "EDT" and "EST" are not real timezones. Those abbreviations are ambiguous and not standard. Prefer to use IANA timezones names (always in the format Region/City, like America/New_York or Europe/Berlin).
So, when you do TimeZone.getTimeZone("EDT"), it usually returns "GMT" (because "EDT" is not recognized, and "GMT" is returned as default). That's because "EDT" is used by more than one timezone, so you must choose specifically which one you're using (I'm using America/New_York in these examples).
Another detail is that in the first 2 formatters you use hh, which means "hour of am/pm" (values from 1 to 12), but the input doesn't have AM/PM designators to properly resolve this. You need to change it to HH ("hour of day", with values from 0 to 23).
// input is in UTC
TimeZone inputZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(inputZone);
Date localStartDate = formatter.parse(startTime);
Date localEndDate = formatter.parse(endTime);
...
// removed the second formatter (it was redundant)
// output is in EST (America/New_York)
// or use TimeZone.getDefault() to get JVM default timezone
TimeZone outputZone = TimeZone.getTimeZone("America/New_York");
SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
monthFormat.setTimeZone(outputZone);
...
SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
dateFormat.setTimeZone(outputZone);
...
SimpleDateFormat dayNameFormat = new SimpleDateFormat("EEEE");
dayNameFormat.setTimeZone(outputZone);
...
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");
timeFormat.setTimeZone(outputZone);
...
System.out.println("My Start date and end date==>>>" + startTimeName + " " + endTimeName);
With this, you're explicity using UTC for input and a specific timezone for output, instead of relying on the JVM default timezone (which can be different in each device and you can't control).
The output is:
My Start date and end date==>>>08:15 AM 09:45 AM
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.
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 the ThreeTenABP (more on how to use it here).
First you can use a org.threeten.bp.Instant to parse the input, because it's in UTC (designated by the Z in the end). Then you use a org.threeten.bp.ZoneId to convert it to a org.threeten.bp.ZonedDateTime:
// output timezone
// or use ZoneId.systemDefault() to get JVM default timezone
ZoneId zone = ZoneId.of("America/New_York");
// parse the inputs
ZonedDateTime startDate = Instant.parse(startTime).atZone(zone);
ZonedDateTime endDate = Instant.parse(endTime).atZone(zone);
Then you can use these objects to get the other fields:
// get month name
System.out.println(startDate.getMonth().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
This is equivalent to MMM pattern, and it will print the month name in the default locale. If you want the month name in a specific language, just use another java.util.Locale value (such as Locale.ENGLISH or any other one as described in the javadoc).
The org.threeten.bp.format.TextStyle defines if the month name will be narrow (usually just one letter), short (usually 2 or 3 letters) or full (the full name). The output varies according to the locale used.
I personally prefer to not use the default locale, because it can be changed without notice, even at runtime. It's always better to specify the locale you want.
To get the day of month, you can choose to get it as an int or as a formatted String (using a org.threeten.bp.format.DateTimeFormatter):
// get day of month as int
int day = startDate.getDayOfMonth(); // 30
// get day of month as formatted string
String dayStr = DateTimeFormatter.ofPattern("dd").format(startDate); // 30
To get the day of week, it's similar to the code used to get the month:
// get day of week
System.out.println(startDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.getDefault()));
The same logic applies here: the TextStyle defines how the name will be (in this case, FULL is equivalen to EEEE, and it prints the full name), and the locale defines the language used.
Finally, to get the corresponding time, you can use another DateTimeFormatter:
// get time
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(fmt.format(startDate)); // 08:15 AM
System.out.println(fmt.format(endDate)); // 09:45 AM
This will the date/time in the timezone you chose for the output.
If you're going to use the JVM default (ZoneId.systemDefault()), just check its value before to make sure it's the one you want (it might not be because this can be changed at runtime, so it's always better to specify one).

How to get android system date and time format in app

How can i get current time format that is set in android. Like it is 12 hrs or 24 hrs. I can easily get date and time and put format on it but i want to get current format of time from android system.
Use the following:
DateFormat.is24HourFormat(context);
Source: https://developer.android.com/reference/android/text/format/DateFormat.html#is24HourFormat(android.content.Context)
If you want to get a String you should use android.text.format.DateFormat
DateFormat dateFormat = android.text.format.DateFormat.getTimeFormat(context);
String = dateFormat.format(new Date());

Android, Right way to programticly format date time as time ago

Example, from 1 min ago
i use api and time response result from Api service as:
{
"date_time":"2016-03-10 03:20:30"
}
Please discuss step by step, And if available how can programticly display it in Arabic format
منذ 15 دقيقة
My Code for date in list view adapter
TextView date_time = (TextView) convertView.findViewById(R.id.date_time_list_home);
date_time.setText(m.dateTime());
First, for any date/time manipulation on Android, I highly recommend using the ThreeTenABP library. This is a back port of the Java 8 java.time.* package, circumventing the notoriously disappointing java.util.Date and java.util.Calendar classes.
To parse your "date_time" using this library, you can use the following code:
// I set the ZoneId to systemDefault, but you should really use the ZoneId of the server
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
.withZone(ZoneId.systemDefault());
Instant instant = formatter.parse(m.dateTime(), Instant.FROM);
Android provides the DateUtils class to display date and time information. This class takes into account system settings such as Locale and 12/24-hour format. Therefore, if the Locale of the device is set to any of the Arabic locales (ar_), the date/time will be displayed in a format suited for it.
String display = DateUtils.getRelativeTimeSpanString(
instant.toEpochMilli(),
Instant.now().toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
The last parameter in getRelativeTimeSpanString is the minimum resolution, so setting DateUtils.MINUTE_IN_MILLIS will not display the difference in seconds.
If you insist on using the Java 7 classes, here is the same code using them:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(m.dateTime());
String display = DateUtils.getRelativeTimeSpanString(
date.getTime(),
new Date(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
If you need a "transition resolution" greater than a single day (i.e. you want to display a date/time that is further than one day in the past as "… days ago") you can use the DateUtils.getRelativeDateTimeString() method instead:
String display = DateUtils.getRelativeDateTimeString(
mContext,
instant.toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL);
Any date that is further back than the transitionResolution (in this case, one week) will be displayed in an appropriate date format, instead of the relative format. The minResolution and transitionResolution can be any long value, DateUtils contains other convenient constants such as MONTH_IN_MILLIS and YEAR_IN_MILLIS.
The last parameter takes an integer for formatting flags. These flags override the default formatting that DateUtils uses for each Locale; view the documentation for more information.

Android - Convert a date to the date format of the device

How do you convert a date to the date format of the device? For example, I have following date: 02/11/2011 (mm/dd/yyyy). How to convert it to the format of the device?
DateFormat has the static methods getDateTimeInstance, getTimeInstance and getDateInstance that are already localized
You might want to consider storing your dates in a more locale-agnostic way as milliseconds.
Then you can use DateFormat.getDateFormat() like this:
dateTextView.setText(DateFormat.getDateFormat(getActivity()).format(new Date(millis)));
According to the documentation for getDateFormat():
Returns a DateFormat object that can format the date in short form (such as 12/31/1999) according to the current locale and the user's date-order preference.
Use SimpleDateFormat to convert a Date into required format.
See this link for more details..
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = format.format(yourdate);

Android - Changing Phone's Timezone

Is is possible to set the phone's timezone programmatically in android? I got this code
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println(sdf.format(calendar.getTime()));
but it does not change the phone's timezone. It only displays the timezone of America/Los Angeles.
The code you are showing simply defines a Calendar instance with a specific format to be used in the app.
It is not possible to change the phone's timezone programmatically.
You could redirect the user to the appropriate settings:
startActivity(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS));
Well, this only changes formatting, so you cannot expect it to change phone's time zone. And no, there are no APIs for changing time or timezone, this is reserved for system apps.

Categories

Resources