Android Date Time Format Pattern - android

I want to know if there is a way to get the format that is currently being used by the system.
As of now i am using the Joda Time library and manually specifying the foramt that i expect the date to be in.
private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(event_date, formatter);
This is of course not the best idea to hardcode the pattern,so is there a way i can get the pattern from the system?

You can use something like this:
DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String pattern = ((SimpleDateFormat)formatter).toPattern();
String localPattern = ((SimpleDateFormat)formatter).toLocalizedPattern();

You can do like this:
String datePattern;
String timePattern;
void loadDateTimePattern(Context context) {
SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateFormat(context);
SimpleDateFormat timeFormat = (SimpleDateFormat) DateFormat.getTimeFormat(context);
datePattern = dateFormat.toPattern();
timePattern = timeFormat.toPattern();
}
DateTimeFormatter timeFormatter = DateTimeFormat.forPattern(timePattern);
DateTimeFormatter timeFormatterFull = DateTimeFormat.forPattern(datePattern + ", " + timePattern);

Related

How to change String that contains month and year only using simpledateformat

im having trouble with SimpleDateFormat. as I'm new to Android Studio Java
I have this string
which is String monthYear = "05/2019".
I want to change it to String monthYear = "May 2019".
may i know how to achieve this by having the result back as string ?
Here's what you can do:
// from string to date
String monthYear = "05/2019";
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/yyyy");
Date date = inputFormat.parse(monthYear);
// from date to string
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM yyyy");
String dateTime = outputFormat.format(date);

Use different time formats according to language

I'm supposed to show different time formats according to the language in my app. When the device is English the user should get the time format like this:
18 March 2018, 2.30 pm
But when the user's device is German he should get the time format like this:
18.03.2018, 14:30 Uhr
Is there any way to do this by formatting the time String with SimpleDateFormat or am I supposed to do this in another way and if so, how am I able to do this?
I didn't think it would work, but it did. Just put the format you like into the string xml file for me it was:
<string name="date_time_format">dd MMMM yyyy, hh.mm a</string>
<string name="date_time_format">dd.MM.yyyy, HH:mm</string>
Then use it in the SDF like this:
SimpleDateFormat fmtOut = new SimpleDateFormat(context.getString(R.string.date_time_format), Locale.getDefault());
for the "Uhr" at the end of the german format i added a placeholder String that looks like this:
<string name="date_time_string">%s</string>
<string name="date_time_string">%s Uhr</string>
and i return the formated date with the String.format() method:
return String.format(context.getString(R.string.date_time_string), fmtOut.format(date));
Try this code snippet. hope it will solve the issue.
java.sql.Date date1 = new java.sql.Date((new Date()).getTime());
SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
SimpleDateFormat formatNowYear = new SimpleDateFormat("yyyy");
SimpleDateFormat sdf12 = new SimpleDateFormat("hh:mm aa");
SimpleDateFormat sdf24 = new SimpleDateFormat("HH:mm");
SimpleDateFormat germanSdf = new SimpleDateFormat("dd.MM.yyyy");
String currentDay = formatNowDay.format(date1);
String currentYear = formatNowYear.format(date1);
String time12 = sdf12.format(date1);
String time24 = sdf24.format(date1);
String germanTime = germanSdf.format(date1);
Calendar mCalendar = Calendar.getInstance();
String currentMonth = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
String engTime = currentDay+" "+currentMonth+" "+currentYear+", "+time12;
String germanFormat = germanTime+", "+time24+" Uhr";
One alternative is to use a java.text.DateFormat:
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH);
The date and time styles (first and second parameters) can be either SHORT, MEDIUM, LONG or FULL. And you can use Locale.getDefault() to get the device's default language, if you want.
I'm not sure which combination of styles give what you want - all of them gave me different outputs and none gave me the one you described.
That's because locale specific formats are embeeded in the JVM, and I'm not sure how it varies among different API levels and devices.
If the solution above works, then it's fine. Otherwise, an alternative is to make specific patterns per locale:
// get device's locale
Locale locale = Locale.getDefault();
String pattern = "";
// check language
if ("en".equals(locale.getLanguage())) {
// english
pattern = "dd MMMM yyyy, h.mm a";
} else if ("de".equals(locale.getLanguage())) {
// german
pattern = "dd.MM.yyyy, HH:mm 'Uhr'";
} else {
pattern = // use some default pattern for other languages?
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
String formattedDate = sdf.format(new Date());
One detail is that, in my JVM, the AM/PM symbols for English locale are in uppercase, so you may want to adjust it by doing:
// change AM/PM to am/pm (only for English)
if ("en".equals(locale.getLanguage())) {
formattedDate = formattedDate.toLowerCase();
}
java.time API
In API level 26, you can use the java.time API. For lower levels, there's a nice backport, with the same classes and functionalities.
This is much better to work with. The code might look similar, but the classes themselves solves lots of internal issues of the old API.
You can first try to get JVM's localized patterns and see if they match your output:
Locale locale = Locale.getDefault();
FormatStyle style = FormatStyle.MEDIUM;
String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(style, style, IsoChronology.INSTANCE, locale);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, locale);
Or do the same as above:
// get device's locale
Locale locale = Locale.getDefault();
String pattern = "";
// check language
if ("en".equals(locale.getLanguage())) {
// english
pattern = "dd MMMM yyyy, h.mm a";
} else if ("de".equals(locale.getLanguage())) {
// german
pattern = "dd.MM.yyyy, HH:mm 'Uhr'";
} else {
pattern = ""; // use some default pattern?
}
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, locale);
String formattedDate = LocalDateTime.now().format(fmt);
In my tests, I've got the same problem of having uppercase AM/PM for English. You can solve this by calling toLowerCase() as above, but this API also allows you to create a more flexible formatter.
And the formatters are thread-safe (while SimpleDateFormat isn't), so you could create a static map of formatters based on the language and reuse them as many times you want:
// map of formatters
Map<String, DateTimeFormatter> formatterMap = new HashMap<>();
// English formatter
Map<Long, String> customAmPmSymbols = new HashMap<>();
customAmPmSymbols.put(0L, "am");
customAmPmSymbols.put(1L, "pm");
DateTimeFormatter f = new DateTimeFormatterBuilder()
// date/time
.appendPattern("dd MMMM yyyy, h.mm ")
// custom AM/PM symbols (lowercase)
.appendText(ChronoField.AMPM_OF_DAY, customAmPmSymbols)
// create formatter
.toFormatter(Locale.ENGLISH);
// add to map
formatterMap.put("en", f);
// German formatter
formatterMap.put("de", DateTimeFormatter.ofPattern("dd.MM.yyyy, HH:mm 'Uhr'", Locale.GERMAN));
// get device's locale
Locale locale = Locale.getDefault();
DateTimeFormatter fmt = formatterMap.get(locale.getLanguage());
if (fmt != null) {
String formattedDate = LocalDateTime.now().format(fmt);
}

Android joda time convert from 24 to 12

I am inserting the date to database like this:
long d = cal.getTimeInMillis();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String time_string_f=dateFormat.format(d);
time_string_f is the string to insert in database , and the output is like:
07/09/2015 20:47:00
I want to get it from database and format it to be 12 hours with am/pm.
So I got this solution from here
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss.SSa");
DateTime jodatime = dtf.parseDateTime(string_date_from_database);
int yy= jodatime.getYear();
I am getting the year just to check if it works.
but it does not work and gives me this error:
07-09 22:34:48.399: I/FFFFF(7165): Invalid format: "07/09/2015 20:47:00" is malformed at "/09/2015 20:47:00"
Value in you database has format MM/dd/yyyy HH:mm:ss - without AM/PM suffix.
So you should parse is without a option and then convert date to 12 hours format.
Example:
String string_date_from_database = "07/09/2015 20:47:00";
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
DateTime jodatime = dtf.parseDateTime(string_date_from_database);
String dateIn12HourFormat = jodatime.toString("MM/dd/yyyy hh:mm:ssa");
// Now 'dateIn12HourFormat' looks like `07/09/2015 08:47:00PM`
You can use simple utility method:
static final DateTimeFormatter hours24 = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
static final DateTimeFormatter hours12 = DateTimeFormat.forPattern("MM/dd/yyyy hh:mm:ssa");
static String convertTo12HoursFormat(String format24hours)
{
return hours12.print(hours24.parseDateTime(format24hours));
}
Usage:
String string_date_from_database = "07/09/2015 20:47:00";
String dateIn12HourFormat = convertTo12HoursFormat(string_date_from_database);
Try like the following.
long d = cal.getTimeInMillis();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
String time_string_f=dateFormat.format(d);

How to create a valid DateTime object from String

I have the following String.
21-Mar-2014
How can i convert this into a valid Joda DateTime object?
I've tried the following with no joy:
DateTimeFormatter formatter = DateTimeFormat.forPattern("d-MMM/Y");
DateTime dt = formatter.parseDateTime(date);
Thanks in advance
Matt
There are already so many question in SO related to this.
Check this.
A genuine joda answer with corrected pattern string and explicit Locale:
String input = "21-Mar-2014";
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yyyy").withLocale(Locale.ENGLISH);
DateTime dt = dtf.parseDateTime(input); // using the default time zone
System.out.println(dt); // 2014-03-21T00:00:00.000+01:00 (my zone: Europe/Berlin)
If you don't need time part (regarding your input!) then I recommend to use:
LocalDate date = dtf.parseLocalDate(input);
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
you can try this
Date date1;
String myFormatString = "MMM-dd-yyyy"; // for example
String Your_Date=txtDate.getText().toString();
SimpleDateFormat df = new SimpleDateFormat(myFormatString);
date1 = df.parse(Your_Date);
you just use the following simple date format
SimpleDateFormat sdf=new SimpleDateFormat("d-MMM-yyyy");
Date date1=sdf.parse("21-Mar-2014");
Try this
DateTimeFormatter formatter = DateTimeFormat.forPattern("d-MMM-yyyy");
DateTime dt = formatter.parseDateTime(date);
System.out.println(dt.toString());

Get preferred date format string of Android system

Does anybody know how to get the format string used by the system when formatting a date using
DateFormat.getLongDateFormat(Context context).format(Date date)
To get the date format pattern you can do:
Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();
I wrote a method to detect this format string. ( work for my case).
public static String getDateFormat(Context context){
// 25/12/2013
Calendar testDate = Calendar.getInstance();
testDate.set(Calendar.YEAR, 2013);
testDate.set(Calendar.MONTH, Calendar.DECEMBER);
testDate.set(Calendar.DAY_OF_MONTH, 25);
Format format = android.text.format.DateFormat.getDateFormat(context);
String testDateFormat = format.format(testDate.getTime());
String[] parts = testDateFormat.split("/");
StringBuilder sb = new StringBuilder();
for(String s : parts){
if(s.equals("25")){
sb.append("dd/");
}
if(s.equals("12")){
sb.append("MM/");
}
if(s.equals("2013")){
sb.append("yyyy/");
}
}
return sb.toString().substring(0, sb.toString().length()-1);
}
EDIT Please check the Mark Melling's answer below https://stackoverflow.com/a/18982842/945808 to have better solution. Mine was just a hack long time ago.
There is a static method in the API that you can call like this:
Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
There is more discussion about it here.
You can use this:
private static DateFormat mDateFormat;
private static DateFormat mTimeFormat;
mDateFormat = android.text.format.DateFormat.getDateFormat(this);
mTimeFormat = android.text.format.DateFormat.getTimeFormat(this);
public static String getSystemDateFormat() {
return ((SimpleDateFormat) mDateFormat).toPattern();
}
public static String getSystemTimeFormat() {
return ((SimpleDateFormat) mTimeFormat).toPattern();
}
public static String getSystemDateTimeFormat() {
return getSystemDateFormat() + " " + getSystemTimeFormat();
}
based on an answer above:
String pattern = Settings.System.getString(getActivity().getContentResolver(),
Settings.System.DATE_FORMAT);
String format;
if (pattern.indexOf("d")<pattern.indexOf("M"))
format = "d/M";
else
format = "M/d";
SimpleDateFormat df = new SimpleDateFormat(format);
and then use the SimpleDateFormat to format your Date objects. It's working for me.
SimpleDateFormat
I use SimpleDateFormat without custom pattern to get actual date and time in preferred format from system:
public static String getFormattedDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat(); //called without pattern
return df.format(c.getTime());
}
returns:
13.01.15 11:45
1/13/15 10:45 AM
...
According to the DateFormat documentation:
To format a date for the current Locale, use one of the static factory
methods:
myString = DateFormat.getDateInstance().format(myDate);
And to format it for a different locale:
myString = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE).format(myDate);
String shortDateFormat = Settings.System.getString(context.getContentResolver(), Settings.System.DATE_FORMAT);

Categories

Resources