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;
}
Related
My database has DATETIME data type, so I need to pass the DATE format to my API parameter. All I found in online is convert date to string type which is not I want
Something like this should work. Your API clearly isn't looking for an actual DATETIME object just a string in the correct format, like so:
public static String getFormattedDateTime(Date date) {
// Get date string for today to get today's jobs
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(date);
}
You can use a method like this if you have a date String rather than a date object. You will parse a string after defining a dateFormat:
public static Date getDateObjectFromDateTime(String dateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date inputDate = null;
try {
inputDate = dateFormat.parse(dateString);
} catch(ParseException e) {
e.printStackTrace();
}
return inputDate;
}
I'm using Room that I retrieve its data from Firebase Realtime database I have "requests" node which contains date node the code works fine but i want to change the date format to "dd-mm-yyyy"
How can I do that ?
public class DateTypeConverter {
#TypeConverter
public static Date toDate(Long value) {
if(null == value){
return null;
}else {
Date date = new Date(value);
return date;
}
}
#TypeConverter
public static Long toLong(Date value) {
return value == null ? null : value.getTime();
}
}
Edit:
I found a solution here
I think that putting the format in resources is best approach
Room storing date in long data type and returning it in Date data type.
Now to show this date you need to convert it into String with "dd-mm-yyyy" format.
You can do this with using SimpleDateFormat class in Java.
public static String formatDate(Date date) {
SimpleDateFormat dateFormat;
// Apply desired format here
dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
Calendar c = Calendar.getInstance();
dateFormat.setTimeZone(TimeZone.getDefault());
c.setTimeInMillis(date.getTime());
return dateFormat.format(c.getTimeInMillis());
}
Now as commented you are using Databinding, you can call this static function directly while setting text for your TextView
Hope this help you!!!
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());
}
From a web service i am getting a date format as 1994-09-11 in my android app i need to display this as Sep 11
My code is as follows
Date date_temp = null;
String d_temp = null;
DateFormat formatter;
static SimpleDateFormat datesdf = new SimpleDateFormat("yyyy MMM dd");
public String changeDateformat(String date_str)
{
Log.e("date_str ",""+date_str);
try
{
date_temp = (Date)formatter.parse(date_str);
Log.e("date_temp ",""+date_temp);
d_temp = null;
d_temp = datesdf.format(date_temp);
Log.e("d_temp ",""+d_temp);
}
catch (ParseException ex)
{
ex.printStackTrace();
}
catch (java.text.ParseException e)
{
e.printStackTrace();
}
return d_temp;
}
When the above method is called, the first log value is been printed(the value which i get from the web), then my app gets crashed saying that
09-10 13:02:44.920: E/AndroidRuntime(3503): java.lang.NullPointerException
09-10 13:02:44.920: E/AndroidRuntime(3503): at xxxxxxxxxxx(Events.java:206)
Here line number 206 is the first line inside try catch of the above method.
What is wrong with my code, pls suggest me.....
DateFormat formatter; <-- it is never initialized. so you are calling a methode on null.
Maybe you want to use:
static SimpleDateFormat datesdf = new SimpleDateFormat("yyyy MMM dd");
Instead of formatter.
You can use string builder
after getting date from web
try this
//wherever you want to set this you can set as below:
enter code here
EditText aa;
aa.setText( new StringBuilder()
// Month is 0 based so add 1
.append(day).append("/")
.append(month + 1).append("/")
.append(year).append(" "));
The DateFormat is not used like that way. You declare a formatter but never initialize it. To format a date, you need to do it like this,
d_temp = DateFormat.format("MMM dd", date_temp).toString();
You need a SimpleDateFormat to convert your date string to date and another SimpleDateFormat to format your date to a new string. Try this code,
public static Date strToDate(String format, String date) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(date);
} catch (ParseException e) {
return null;
}
}
public String changeDateformat(String date_str) {
Date t = strToDate("yyyy-MM-dd", date_str);
return DateFormat.format("MMM dd", t).toString();
}
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);