Formatting date and time as in "Settings - Date and time" - android

There seems to be many ways to format date and time in Android - but none exactly the way I want ;-)
The methods I have been able to find involve the Locale (directly or indirectly) - but the correct way must be to use what the user has configured in "Settings - Date and time".
Using for example:
String res = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT, java.text.DateFormat.MEDIUM).format(date);
Log.d("", res);
logs: 4/9/13 12:11:34 PM
and
res = android.text.format.DateUtils.formatDateTime(getActivity(), date.getTime(), android.text.format.DateUtils.FORMAT_SHOW_TIME | android.text.format.DateUtils.FORMAT_SHOW_DATE | android.text.format.DateUtils.FORMAT_SHOW_YEAR);
Log.d("", res);
logs: 12:11 April 9, 2013
BUT this is not how it is configured and when I look at a file's date and time it is written as: 09/04/2013 12:11
So how do I get the formatting strings (like "yyyy-MM-dd" and "HH:mm") configured in "Settings - Date and time" or alternatively, how do I get a Date formatted according to these rules?

Try to use below code:
public static String convertDateToUserFormat(final Date inputDate) {
if (inputDate != null) {
return getDateFormat().format(inputDate);
}
return null;
}
private static DateFormat getDateFormat() {
final String format = Settings.System.getString(context.getContentResolver(),
Settings.System.DATE_FORMAT);
if (TextUtils.isEmpty(format)) {
return android.text.format.DateFormat
.getDateFormat(context);
}
return new SimpleDateFormat(format);
}

Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
formattedDate = formatter.parse(yourDateString);
For more info on DateFormatter check out the developer doc

here is the example for date format
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("format 1 " + sdf.format(date));
sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));
u can follow this link for more info enter link description here

Related

Android DateFormatter print Eastern Daylight Time instead of EDT

So Im trying to print the string "Eastern Daylight Time" instead of EDT . This should be dynamic and not hardcoded. Looking into DateFormatter class did not lead me to an answer that worked.
Here was an example that allows me to format but did not lead me to my specific answer.
I am getting the date back in the following format -
2013-06-08T00:00:00-04:00
Here are somethings that I have tried -
1)
String dateString = changeFormatDateStringWithDefaultTimeZone(paymentConfirmation.getTransactionDate(),
"yyyy-MM-dd'T'HH:mm:ssZ",
"M/d/yyyy hh:mm a zz");
public static String changeFormatDateStringWithDefaultTimeZone(String value, String ip_format, String op_format) {
if (value == null)
return null;
try {
SimpleDateFormat opSDF = new SimpleDateFormat(op_format, Locale.US);
opSDF.setTimeZone(TimeZone.getDefault());
SimpleDateFormat inSDF = new SimpleDateFormat(ip_format, Locale.US);
Date date = inSDF.parse(value);
return(opSDF.format(date));
} catch (Exception e) {
Log.e("Err", "Failed to convert time "+value);
e.printStackTrace();
}
return null;
}
2)
Date today = Calendar.getInstance().getTime();
String todayString = DateUtils.convertDateToStringWithTimeZone(today);
public static String convertDateToStringWithTimeZone(Date date){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = df.format(date);
dateString += " " + TimeZone.getDefault().getDisplayName(false, TimeZone.LONG);
return dateString;
}
These always print timezone as EDT and I want the string Eastern Daylight Time. Can anyone help me out with this?
Okay, based on your last edit of the question, the solution should be like this:
case 1)
The output pattern should be changed to "M/d/yyyy hh:mm a zzzz" (note the count of z-symbols to enforce the full zone name). Depending on the date and the underlying timezone, the formatter SimpleDateFormat will automatically determine if the daylight or the standard name is to be used.
case 2)
Use TimeZone.getDefault().getDisplayName(true, TimeZone.LONG) to enforce the long daylight name. If your default timezone is "America/New_York" then such an expression should print "Eastern Daylight Time". Note that the boolean parameter has been changed to true.

Android:Display time after adding GMT time zone

I am working on a App in which i want to display notification time.
I can display notification time but not able to add time zone in it.
My current location is Pakistan and i want to add GMT+5:00
My code is attached
String currentDateTimeString = DateFormat.getTimeInstance().format(notif.At);
textViewTime.setText(currentDateTimeString);
in this code, notif.At is dateTime variable. I also attached screenshot of my app, i want to ask you , how to add timeZone value in notif.At. Thanks!
Update
You mark time with timezone in order to solve internationalization problem, I understand, right?
If so, I think it could be better to convert your date to UTC date. When you change to another timezone, just convert this UTC Date to local.
public static Date localToUtc(Date localDate) {
return new Date(localDate.getTime()-TimeZone.getDefault().getOffset(localDate.getTime()));
}
public static Date utcToLocal(Date utcDate) {
return new Date(utcDate.getTime()+TimeZone.getDefault().getOffset(utcDate.getTime()));
}
Old answer
If your notif.At is Dateobject, it's a same question actually:
TimeZone tz = TimeZone.getDefault();
Date date = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
String result = sdf.format(date);
Log.d("Date ", "date: " + result + " " + tz.getDisplayName(false, TimeZone.SHORT));
print:
date: 2015-03-31 18:45:28 GMT+08:00
You can try java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
LocalDateTime pst = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:00"));
LocalDateTime is = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:30"));

Format date to local setting but only for month and day

My date is in a string in the format "2013-12-31". I want to convert this to a local date based upon the user's device setting but only show the month and day. So if the user's device is set to German, the date should be converted to "31.12". In Germany, the day comes first followed by the month. I don't want the year to be included.
For Build.VERSION.SDK_INT < 18 I could not find a way to obtain a month/day format that obeys user preferences. This answer works if you are willing to accept month/day in user's locale default pattern (not their preferred order or format). My implementation uses the full numeric format in versions less than 18 or if any issues are encountered in the following carefully programmed series of steps.
Get user's numeric date format pattern as String
Reduce pattern to skeleton format without symbols or years
Obtain localized month/day format with DateFormat.getBestDateTimePattern
Reorder localized month/day format according to user preferred order. (key assumption: days and months can be naively swapped for all localized numeric formats)
This should result in a month/day pattern that obeys user's preference in localized formatting.
Get user date pattern string per this answer:
java.text.DateFormat shortDateFormat = DateFormat.getDateFormat(context);
if (shortDateFormat instanceof SimpleDateFormat) {
String textPattern = ((SimpleDateFormat) shortDateFormat).toPattern();
}
Reduce pattern to day/month skeleton by removing all characters not 'd' or 'M', example result:
String skeletonPattern = 'ddMM'
Get localized month/day format:
String workingFormat = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeletonPattern);
(note: this method requires api 18 and above and does not return values in user-preferred order or format, hence this long-winded answer):
Get user preferred date order ('M', 'd', 'y') from this method:
char[] order = DateFormat.getDateFormatOrder(context);
(note: I suppose you could parse the original pattern to get this information too)
If workingFormat is in the correct order, your job is finished. Otherwise, switch the 'd's and the 'M's in the pattern.
The key assumption here is that days and months can be naively swapped for all localized numeric formats.
DateFormat monthDayFormat = new SimpleDateFormat(workingFormat);
I think, this is the simplest solution for apps targeting API > 17:
dateFormat = SimpleDateFormat(DateFormat.getBestDateTimePattern(Locale.getDefault(), "MMMM dd"), Locale.getDefault())
A bit late, bit I also faced the same issue. That is how I solved it:
String dayMonthDateString = getDayMonthDateString("2010-12-31", "yyyy-MM-dd", Locale.GERMANY);
Log.i("customDate", "dayMonthDateString = " + dayMonthDateString);
private String getDayMonthDateString(String dateString, String dateFormatString, Locale locale)
{
try
{
boolean dayBeforeMonth = defineDayMonthOrder(locale);
String calendarDate = dateString;
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
Date date = dateFormat.parse(calendarDate);
SimpleDateFormat newDateFormat;
if (dayBeforeMonth)
{
newDateFormat = new SimpleDateFormat("dd.MM", locale);
}
else
{
newDateFormat = new SimpleDateFormat("MM.dd", locale);
}
return newDateFormat.format(date);
}
catch (ParseException e)
{
e.printStackTrace();
}
return null;
}
private boolean defineDayMonthOrder(Locale locale) throws ParseException
{
String day = "10";
String month = "11";
String year = "12";
String calendarDate = day + "." + month + "." + year;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy");
Date date = format.parse(calendarDate);
String localizedDate = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale).format(date);
int indexOfDay = localizedDate.indexOf(day);
int indexOfMonth = localizedDate.indexOf(month);
return indexOfDay < indexOfMonth ? true : false;
}
Let me know of any questions you could have related to the solution.
Keep it simple, we already have a method for this (API 18+):
String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "yyyy-MM-dd");
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
String output = format.format(currentTimeMs);
Today its 2019 July 18:
In Europe, the output will be
18.07.2019
In the US, the output will be:
07/18/2019
This works:
String dtStart = "2010-12-31";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dtStart);
SimpleDateFormat df = (SimpleDateFormat)
DateFormat.getDateInstance(DateFormat.SHORT);
String pattern = df.toLocalizedPattern().replaceAll(".?[Yy].?", "");
System.out.println(pattern);
SimpleDateFormat mdf = new SimpleDateFormat(pattern);
String localDate = mdf.format(date);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM");
try {
Date date = inputFormat.parse("2013-12-31");
String out = outputFormat.format(date);
// out is 31.12
} catch (ParseException e) {
e.printStackTrace();
}

Convert DateTime object java to Json string

I want to convert date time object in java to json string in format as below:
{"date":"/Date(18000000+0000)/"}
I did like this but it didn't give me the format i desired:
JSONObject object = new JSONObject();
object.put("date",new Date());
and the result of object.toString()
{"date":"Fri May 04 11:22:32 GMT+07:00 2012"}
i want the string "Fri May 04 11:22:32 GMT+07:00 2012" transform to "/Date(18000000+0000)/" (18000000+0000 here is just a example).
Thanks for your help.
Here is my solution, although it is not a good way, but I finally find a workable solution.
SimpleDateFormat format = new SimpleDateFormat("Z");
Date date = new Date();
JSONObject object = new JSONObject();
object.put("date", "/Date(" + String.valueOf(date.getTime()) + format.format(date) + ")/");
public static String convertToJsonDateTime(String javaDate)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date currentDate = null;
try {
currentDate = dateFormat.parse(javaDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long time =currentDate.getTime();
return "\\/Date("+time+"+0000)\\/";
}
My solution : I think this is the simplest Way
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
yourJsonObject.accumulate("yourDateVarible",dateFormat.format(new Date()));
The date format that you want is /Date(<epoch time><Time Zone>)/.
You can get the epoch time in java using long epoch = System.currentTimeMillis()/1000;(found at this link) and the time zone you can get by using the date and time patteren as Z. Then combine all the strings into one and store it to the Json Object.
Other possibility is that the time you are getting from iOS device may be of the pattern yyMMddHHmmssZ as got from here. Check the output on the iOS device at different times and identify the correct pattern.
From json.org's description of JSONObject:
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
This library doesn't support the "complex" mapping of a Date to a JSON representation. You'll have to do it yourself. You may find something like SimpleDateFormat helpful.
If your format like this -> "DDmmYYYY+HHMM"
DD -> Day (2 Digit)
mm -> Month (2 Digit)
YYYY -> Year (4 Digit)
HH -> Hour
MM -> Minute
Than you can do like this:
SimpleDateFormat format = new SimpleDateFormat("DDmmYYYY+HHMM");
JSONObject object = new JSONObject();
object.put("date", "/Date(" + format.format(new Date()) + ")/");
I suppose that's a representation of ISO international date-time format.
YYYYMMDD+HHMM
I think now you will be able to create that string
may be like,
Date d=new Date();
String tmp="";
tmp="/Date("d.getYear()+""+d.getMonth()+""+d.getDate()+"+"+d.getHours()+""+d.getMinutes()+")/";
Upgrade one of the previous answer:
public static String convertToJsonDateTime(Date dateToConvert) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
long time = dateToConvert.getTime();
return "/Date(" + time + "+0000)/";
}

Date format : Android Contacts Birthday Anniversary

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.

Categories

Resources