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!!!
Related
I want to use Date type as Id in Room database, The main reason for this is to be able to check if this date is today. Any suggestion is appreciate
#Entity
data class DailyCount(#PrimaryKey
var date:DateTime,// JodaTime
var summ: MutableLiveData<Double>? = MutableLiveData())
I want to make query like this:
#Query("update DailyCount set summ = :sum where date = :dailyCount") //update if date is today
fun apdateCash(dailyCount: DateTime, sum: Double)
Just use SimpleDateFormatter
String jsonDateStr = "03-09-2019 05:45:10"
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy");
try {
return fmt.parse(jsonDateStr);
} catch(ParseException pe) {
return //generate different unique ID like GUID random maybe;
}
Now if you have a date object first, and you need to zero it out, you could do:
Date dateObject = Date("03-09-2019 05:45:10") //pseudo for visual
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy");
try {
String dateWithZeroedTime = fmt.format(dateObject)
return fmt.parse(dateWithZeroedTime) //"03-09-2019 00:00:00"
} catch(ParseException pe) {
return //generate different unique ID like GUID random maybe;
}
Happy Coding!
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;
}
Tried to convert firestore timestamp to string and I got this!
I tried String date = FieldValue.serverTimestamp().toString(); and instead of time stamp I got this as shown in Screenshot1
The date inside a Firestore database must be stored as a Date object as explained here. Assuming that you have public getter named getDate() inside your model class, to print the date, please use the following code:
Date date = yourModelClass.getDate();
if (date != null) {
DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
String creationDate = dateFormat.format(date);
Log.d("TAG", creationDate);
}
What you are actually printing there is the address of the FieldValue class from the memory.
okay so the toString() will not output the date formatted since the object returned by the statement FieldValue.serverTimestamp() is a Date object so you can do something like this to handle date formatting.
Date now = FieldValue.serverTimestamp();
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
Log.i("Format 1: ", dateFormatter.format(now));
I'm having a problem inserting some datetime values in my sqlite database.
I have two datepickers, i can choose a date, but after that, when I insert it into my database, I don't know why but the row for the 2 dates have the current date.. How can I do to insert the date I selected in the datepicker ?
In my database, I declared those columns as DATETIME.
Here's my get-setter class for the dates:
public String getDate_debut() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public void setDate_debut(String date_debut) {
this.date_debut = date_debut;
}
public String getDate_fin() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public void setDate_fin(String date_fin) {
this.date_fin = date_fin;
}
Here's how I get the date of one datepicker. I'm not sure about the way I format my string, and if I need to format or if I can just add as a string.
private DatePickerDialog.OnDateSetListener datepickerdernier
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
year_x2 = year;
//les DatePicker
month_x2 = month +1;
day_x2 = dayOfMonth;
datefin = (TextView)findViewById(R.id.TVDatePickerDernier);
datefin.setText(year_x2+"-"+month_x2+"-"+day_x2);
}
};
String date2 = datefin.getText().toString();
//im not sure about the following lines
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date_dernier = dateFormat.parse(date2);
And at the end I insert it :
Cours c = new Cours();
c.setBranche_cours(selectedBranche);
c.setDate_fin(date2); //should i set the string ?
dbhelper.Open();
dbhelper.insertCours(c);
How can I insert in my db the date I selected and not the current date?
#UPDATE - **How can I update the date that is inserted ?
I have another activity, and i want to modify the dates I chose before, but I'm not able..
Here's my sqlite method :
public void updateCours(Date olddatedebut, Date newdatedebut, Date olddatedernier, Date newdatedernier)
{
Open();
db.execSQL("UPDATE "+TABLE_COURS+" set "+COLONNE_DATEPREMIER+"=date('"+newdatedebut+"') where "+COLONNE_DATEPREMIER+"=date('"+olddatedebut+"')");
db.execSQL("UPDATE "+TABLE_COURS+" set "+COLONNE_DATEDERNIER+"=date('"+newdatedernier+"') where "+COLONNE_DATEDERNIER+"=('"+olddatedernier+"')");
}
And how I pass that to my method on my activity:
//this is the new date of the 2nd datepicker
String datedernier = convertDateFormat(datenew2, "yyyy-MM-dd", "dd-MMM-yyyy");
//this is the new date of the 1st datepicker
String datepremier = convertDateFormat(datenew1, "yyyy-MM-dd", "dd-MMM-yyyy");
String date_debutold= intent.getExtras().getString("date_debut");
String date_finold=intent.getExtras().getString("date_fin");
//this is the current date recorded in my database from my datepicker
String date_debut1= convertDateFormat(date_debutold, "yyyy-MM-dd", "dd-MMM-yyyy");
//this is the current date recorded in my darabase from my 1st datepicker
String date_fin1= convertDateFormat(date_finold, "yyyy-MM-dd", "dd-MMM-yyyy");
//nouvelledatedebut
Date date_premier= new Date(datepremier);
Date date_dernier = new Date(datedernier);
Date date_premier2 = new Date(date_debut1);
Date date_fin2 = new Date(date_fin1);
dbhelper.Open();
dbhelper.updateCours(selected_brancheold,selectedBranchenew,date_premier2,date_premier,date_fin2,date_dernier,
Thats because you are making some logic on the getter method and setting the new Date(), that will override the date on the date_fin attribute. When you make insertCours probabily this method will try to find all the get methods for the object you are trying to insert. Try change this:
public String getDate_fin() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(this.date_fin);
}
to this
public String getDate_fin() {
return this.date_fin;
}
If you still want to add a format to the Date (String), you can still make it on the getter method, but I don't recommend it.
try this
public static String convertDateFormat(String date, String curFormat, String desFormat){
String newFormat = null;
Date frmtDate = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(curFormat);
frmtDate = sdf.parse(date);
SimpleDateFormat formatter = new SimpleDateFormat(desFormat);
newFormat = formatter.format(frmtDate);
} catch (Exception e) {
newFormat = date;
}
return newFormat;
}
sample
String result = convertDateFormat(date2, "yyyy-MM-dd", "dd-MMM-yyyy");
c.setDate_fin(result);
Each value stored in an SQLite database (or manipulated by the
database engine) has one of the following storage classes:
NULL. The value is a NULL value.
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8
bytes depending on the magnitude of the value.
REAL. The value is a floating point value, stored as an 8-byte IEEE
floating point number.
TEXT. The value is a text string, stored using the database encoding
(UTF-8, UTF-16BE or UTF-16LE).
BLOB. The value is a blob of data, stored exactly as it was input.
There is no DATETIME. SQlite store it as a TEXT. You can't add a day. You have to read it and parse it. And the same goes when you store it. You have to parse it.
Hope it was usefull.
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;
}