I have a date/time that is specified in milliseconds which is retrieved by:
Calendar.getInstance().getTimeInMillis();
I would like to format this to a string that represents the date and time in whatever the local format is on the device. For example:
US: 12/15/2013 10:30 pm
Germany: 15.12.2013 22:30
I shouldn't have to specify the formatting such as:
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, yyyy h:mm a");
Is there an API that handles local formatting?
See this code
String myformat = android.provider.Settings.System.getString(getContentResolver(), android.provider.Settings.System.DATE_FORMAT);
DateFormat dateFormat;
if (TextUtils.isEmpty(myformat)) {
dateFormat = android.text.format.DateFormat.getMediumDateFormat(getApplicationContext());
} else {
dateFormat = new SimpleDateFormat(format);
}
so dateformat will match with your device date
check DateFormat. Specially
public static final DateFormat getDateInstance(int style,
Locale aLocale)
Here is an example. See if it can help.
I guess this is what you are looking for:
Locale locale = Locale.getDefault();
Date today = new Date();
SimpleDateFormat.SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG, SimpleDateFormat.LONG, locale).format(today));
where you need to check locale and pass its value accordingly.
As an option you can store a format string in string resources to make it available via
getResources().getString(R.string.format)
Then just put strings you need to locale folders, for example:
res/values-en/strings.xml
res/values-fr/strings.xml
Related
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);
}
I want to get current time specifically in English to save it in Database,
to get Current time i use function
private String get_current_Time() {
String CURRENT_TIME_FORMAT = "yyyy_MM_dd_HH_hh_mm_ss_a_MMMM_MMM_EEEE_EE";
return (String) DateFormat.format(CURRENT_TIME_FORMAT, Calendar.getInstance().getTime());
}
but when i set Locale to different language it gives me current time in that language.
for example if i set
conf.setLocale(new Locale("mr"));
it gives me date in marathi. I specifically want it in English. How to do it.
And Also how to change the language of Date once it is saved.I mean if I have saved date in English and while display i want that date to be shown in some other language, how to do it.?
As ADM suggested. new function that worked
public String get_current_Time() {
String CURRENT_TIME_FORMAT = "yyyy_MM_dd_HH_hh_mm_ss_a_MMMM_MMM_EEEE_EE";
SimpleDateFormat dateFormat = new SimpleDateFormat(CURRENT_TIME_FORMAT, Locale.ENGLISH);
return dateFormat.format(Calendar.getInstance().getTime());
}
So now it always returns Date in English
This should fix your issue! Try any of these
here is a simple tutorial
For java.util.Date, just create a new Date()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
log.d(dateFormat.format(date)); //2016/11/16 12:08:43
For java.util.Calendar, uses Calendar.getInstance()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
log.d(dateFormat.format(cal)); //2016/11/16 12:08:43
For java.time.LocalDateTime, uses LocalDateTime.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
log.d(dtf.format(now)); //2016/11/16 12:08:43
For java.time.LocalDate, uses LocalDate.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
log.d(dtf.format(localDate)); //2016/11/16
I create a URL using a given date as a parameter.
This date is created thusly:
final String from = DateFormat.format("dd.MM.yyyy", date).toString();
This string is added to a URL:
+ "&from=" + from
Errors started appearing in my Crashlytics reporter. To debug, I set it to report the URLs that were being sent.
How is it that the URL being generated can look like this: &from=٢٩.٠٦.٢٠١٦?
As Blackbelt has noted, the date is formatted as such because of the Locale on the user's phone.
You could simply convert the date to the format you want specifying English locale.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
String from = dateFormat.format(date);
That's due to your phone's default Locale.
Use this to get the date in correct format :
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
String from = simpleDateFormat.format(date);
Read more about SimpleDateFormat here.
I know how SimpleDateFormat works, by grabbing sdfDateTime.format(new Date(System.currentTimeMillis())); which is today's date from the System. Can SimpleDateFormat format a date by grabbing a string? Let's say you had a string: String dateStr = "04/05/2012"; how would you format that into: "April 5, 2012"?
DateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy");
inputFormat.setLenient(false);
DateFormat outputFormat = new SimpleDateFormat("MMMM dd, yyyy");
outputFormat.setLenient(false);
String inputDateAsString = "04/05/2012";
Date inputDate = inputFormat.parse(inputDateAsString);
System.out.println(outputFormat.format(inputDate));
You can't just grab an arbitrary string and figure out what its format is.
check this one, it is very helpful library, easy to use & extend for such needs
https://bitbucket.org/dfa/strtotime/wiki/Home
Working on Contact birthday and Anniversary:
I get details and birthday like this 12.2.2012 or 12/2/2012 or 12-02-2012 or 2/12/12
Question:
Is the date Format same across all Samsung Phones. IF yes what is the date format.
(Guess won't work on all Android phones as birthday dates are stored in many different format)
How to identify the date format like if the date is 12.2.2012 or Feb 12 2012 or any other date string pattern. Is it of format "yyyy-MM-dd" or "MMM dd, yyyy" or any other?
ex: if date is "Feb 12 2012" then date format is "MMM dd yyyy"
Unfortunately it seems different apps/vendors use different formats. My solution for this is to try parsing different formats until i either find the right one or give up.
Here is some sample code:
public static final SimpleDateFormat[] birthdayFormats = {
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyyMMdd"),
new SimpleDateFormat("yyyy.MM.dd"),
new SimpleDateFormat("yy-MM-dd"),,
new SimpleDateFormat("yyMMdd"),
new SimpleDateFormat("yy.MM.dd")
new SimpleDateFormat("yy/MM/dd"),
new SimpleDateFormat("MM-dd"),
new SimpleDateFormat("MMdd"),
new SimpleDateFormat("MM/dd"),
new SimpleDateFormat("MM.dd"),
};
.....
Date birthday = null;
for (SimpleDateFormat f : birthdayFormats) {
try {
birthday = f.parse(birthdaystr);
if (birthday!=null) {
contact.setBirthday(birthday);
break;
}
} catch (Exception e) {
continue;
}
}
Use DateFormat.getDateInstance(int style, Locale locale) instead of creating your own patterns with SimpleDateFormat.
Another way that u want to get date in String and after pass in below code
String dateStr = "04/05/2010";
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = curFormater.parse(dateStr);
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy");
String newDateStr = postFormater.format(dateObj);
The date is stored as "YYYY-MM-DD".
Use the date formater class to convert it into any format you need.
When you want to update put it in the same format as you have read.