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);
Related
I have an API contains string date with this format "/Date(1527677209864)/", how can I get the date and time to be used in Android app
You can use Date with the epoch number as a parameter in the constructor.
First you have to strip /Date( and )/ from the string, this you can do with regex.
Pattern pattern = Pattern.compile("\\D+([0-9]+)\\D+");
Matcher matcher = pattern.matcher("/Date(1527677209864)/");
if (matcher.matches()) {
long timestamp = Long.parseLong(matcher.group(1));
Date actualDate = new Date(timestamp);
}
I'm assuming that 1527677209864 value is a timestamp, right?
Try this function:
public static String getDateAndTime(#NotNull Context context, long timestamp) {
Date date = new Date(timestamp * 1000);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
DateFormat df = new SimpleDateFormat(getTimeFormat(context), Locale.getDefault());
return df.format(date);
}
Let me know if this is what you were looking for.
Remove the prefix /Date( and suffix )/. Use the result to initialize a java.util.Date.
String dt = "/Date(1527677209864)/";
dt = dt.substring(6, dt.indexOf(")/"));
long timestamp = Long.parseLong(dt);
Date date = new Date(timestamp);
Use SimpleDateFormat to format this date to your required format.
We have to filter the timeInMillis value from the string and convert it to long so that we can use or set it in calendar and get the date object.
Date convertToDate(String input) {
// input = "/Date(1527677209864)/";
String timeString = input.substring(6, input.length() - 2);
Long time = Long.parseLong(timeString);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
return calendar.getTime();
}
Then we can format the date object to string according to our desire patter or format.
String convertDateToString(Date date, String pattern) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
return formatter.format(date);
}
Try this
String jsonDate = "/Date(1527677209864)/";
jsonDate = jsonDate.substring(6, 13);
int unix_timestamp = Integer.parseInt(jsonDate);
Date date = new Date(unix_timestamp);
recently I get String "23:00" .
I know convert string to Date
private String strtime;
private Date datetime;
SimpleDateFormat simtime = new SimpleDateFormat("HH:mm");
datatime = simtime.parse(strtime);
datetime is --> `Thu Jan 01 23:00:00 GMT+09:00 1970
but I want only get 23:00
how to use convert date to simpledateformat?
My answer below may not help people but can help #hyunwookcho somehow.
I think you want to compare that HH:mm to current time. So I recommend you to change to other way: Compare that String with current HH:mm.
private String strtime = "23:00";
private String currentHours = "";
SimpleDateFormat simtime = new SimpleDateFormat("HH:mm");
currentHours = simtime.format(Calendar.getInstance().getTime());
if (strtime.equals(currentHours)){
//same hours
}else{
//diff hours
}
UPDATE
If you want to compare between 2 points of time. I suggest you use this
String strtime1 = "23:00";
String strtime2 = "17:00";
String currentHours = "";
String[] strs_time1 = strtime1.split(":");
String[] strs_time2 = strtime2.split(":");
Calendar c_time1 = Calendar.getInstance();
c_time1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strs_time1[0]));
c_time1.set(Calendar.MINUTE, Integer.parseInt(strs_time1[1]));
Calendar c_time2 = Calendar.getInstance();
c_time2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strs_time2[0]));
c_time2.set(Calendar.MINUTE, Integer.parseInt(strs_time2[1]));
Calendar currentCal = Calendar.getInstance();
if (currentCal.getTimeInMillis() >= c_time2.getTimeInMillis() && currentCal.getTimeInMillis() <= c_time1.getTimeInMillis()){
// FIRE IN THE HOLE
}
public static final String TimeFormate = "hh:mm a";
public static String getCurrentDateTime() {
SimpleDateFormat from = new SimpleDateFormat(TimeFormate);
from.setTimeZone(TimeZone.getDefault());
String current = from.format(new Date());
return current;
}
it will help you for sure, It will provide you your perspective time format
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);
I am trying to convert server date string to my local/device set local time but without success. I am using Joda time library.
What i am trying to do:
private static String FORMAT_DATE_SERVER = "YYYY-MM-dd'T'HH:mm:ssZ";
public static DateTime parseServerDateToLocal(String raw_date) {
DateTime result = DateTime.parse(raw_date, DateTimeFormat.forPattern(FORMAT_DATE_SERVER)).withZone(DateTimeZone.getDefault());
return result;
}
Still returns the DateTime from the server. I cant manage to make it to return the proper hour/datetime.
I read many post about this, but i didnt manage to make it simple, clean and working.
The solution i have found:
in your application class, or somewhere else, initialise JodaTimeAndroid:
JodaTimeAndroid.init(this);
after this initialisation the date will be automatically converted to your zone, with proper offset. This is how you parse the data then:
private static String FORMAT_DATE_SERVER = "yyyy-MM-dd'T'HH:mm:ssZ";
private static String raw_date = "2015-06-18T08:52:27Z";
public static DateTime parseServerDateToLocal(String raw_date) {
return DateTime.parse(raw_date, DateTimeFormat.forPattern(FORMAT_DATE_SERVER));
}
In my case, with offset (+2h), the returned data is:
2015-06-18T10:52:27.000+02:00
Try this code
Example
Converting a date String of the format "2011-06-23T15:11:32" to out time zone.
private String getDate(String dateString) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = null;
try {
value = formatter.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy hh:mmaa");
dateFormatter.setTimeZone(TimeZone.getDefault());
String dt = dateFormatter.format(value);
return dt;
}
I have a string which returns the date and time as 2012-11-08 12:45:30 . I need to get the date and time in separate strings and then the date has to be shown in the format which is there in the Phone's Date and Time settings.
Here is the code which I have tried so far:
date value from db is 2012-11-08
I am getting the date format in phone's settings as
String datefrmt = Settings.System.getString(
context.getContentResolver(), Settings.System.DATE_FORMAT);
the code to apply this format to the obtained date from db is:
SimpleDateFormat sdf = new SimpleDateFormat(datefrmt);
java.util.Date date_1 = sdf.parse("2012-11-08");
String s = sdf.format(date_1);
I am getting the month and day properly but the year its returning something randomly and thats not a correct value. Can anyone please guide me where am I going wrong. Thanks
If you have 2012-11-08 12:45:30 string and you want to parse it to Date object and change its format to another (system format for example or 2012-11-08 format):
try {
String yourString="2012-11-08 12:45:30";
//first we parse input date string and create Date object
String inputDateString ="yyyy-dd-MM hh:mm:ss";
SimpleDateFormat inputDateFormat = new SimpleDateFormat(inputDateString);
java.util.Date date = inputDateFormat.parse(yourString);
//log
Log.e(getClass().getName(), inputDateFormat.format(date));
//create system date format
String dateformt = Settings.System.getString( this.getContentResolver(), Settings.System.DATE_FORMAT);
//if its for some reason==null let it be "yyyy-dd-MM"
if(dateformt==null){
dateformt="yyyy-dd-MM";
}
SimpleDateFormat systemDateFormat = new SimpleDateFormat(dateformt);
String outputString = systemDateFormat.format(date);
//log
Log.e(getClass().getName(), outputString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use the simpleDateFormat as:
SimpleDateFormat simpDate = new SimpleDateFormat(datefrmt,
Locale.ENGLISH);
String s = simpDate.format(new Date());
for reference, you can refer to developer site:
for more information refer this link
Since your DB date is in yyyy-MM-dd, don't use the dynamic format to get the date, otherwise it will crash(throw parse exception), instead use the static format as below to get the date. You may use the dynamic format to convert the string as below:
//use static format to convert into date from static formatted data in db
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date_1 = sdf1.parse("2012-11-08");//got the date
//use the dynamic format to convert into string
SimpleDateFormat sdf2 = new SimpleDateFormat(datefrmt);
String s = sdf2.format(date_1);
Since final String format = Settings.System.getString(getActivity().getContentResolver(), Settings.System.DATE_FORMAT);//may be NULL
So I customized my function as below for general purposes
#SuppressLint("SimpleDateFormat")
public String getCurrentShortDateFormat() {
final String[] SFs = new String [] {
"MM/dd/yyyy",
"dd/MM/yyyy",
"yyyy/MM/dd"
};
final Date date = new Date(24638400000L);//24638400000=Oct/13/1970; 0==Jan/1/1970
java.text.DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext());
String current = shortDateFormat.format(date);
SimpleDateFormat which = new SimpleDateFormat();
for (int i = 0; i < SFs.length; i++) {
which.applyPattern(SFs[i]);
if (which.format(date).compareTo(current)==0)
return SFs[i];
}
return null;
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "----- onResume.CurrentShortDateFormat-----" + getCurrentShortDateFormat());
}