Wrong datPicker format in editText - java

I have a datePicker that I want to display in the editText when I take the date from it, it has the wrong format.
For example, I
Jan / 01/2020
I choose.
But inside text editing
It shows 2020/0/1 instead of 2020/01/01
open datePicker:
new SpinnerDatePickerDialogBuilder()
.context(AddProjectActivity.this)
.callback(AddProjectActivity.this)
.spinnerTheme(R.style.NumberPickerStyle)
.showTitle(true)
.showDaySpinner(true)
.defaultDate(2017, 0, 1)
.maxDate(2100, 0, 1)
.minDate(2020, 0, 1)
.build()
.show();
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
meEdtDate.setText(year + "/" + monthOfYear + "/" + dayOfMonth);
date = getDate(year, monthOfYear, dayOfMonth);
}
private Date getDate(int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, monthOfYear, dayOfMonth);
return calendar.getTime();
}
set date to editText:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String dateStr = simpleDateFormat.format(projectEntity.getDate());
meEdtDate.setText(dateStr);

Here is a solution using classes from the current package, java.time, for date handling.
You can create a LocalDate from year, month and day like this
private static LocalDate getDate(int year, int monthOfYear, int dayOfMonth) {
return LocalDate.of(year, monthOfYear, dayOfMonth);
}
And then format it into a String like this
LocalDate date = getDate(2020, 1, 1);
String dateString = date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

Related

Cannot get data from SQLite Room Database using dates

I have a typeconverter that goes like this
public class DateConverter {
#TypeConverter
public static Date convertLongToDate(Long dateLong) {
return dateLong == null ? null : new Date(dateLong);
}
#TypeConverter
public static Long convertDateToLong(Date date) {
return date == null ? null : date.getTime();
}
...
}
And I use it in my database
#Database(entities = { LoginEntity.class,
Transaction.class,
UnsentTagNumbers.class }, version = 11, exportSchema = false)
#TypeConverters(DateConverter.class)
public abstract class ApplicationDatabase extends RoomDatabase {
public abstract LoginDao loginDao();
...
}
In inserting the transaction to the database, I do it like so.
public void recordTransaction() {
transaction.setTransactionDate(Calendar.getInstance().getTime()); <==== Please take note on the way that I use the current date.
transaction.setTransactionType(getApplication().getString(R.string.exit_scan));
...
transactionRepository.insert(transaction);
}
In my DAO
#Query("SELECT * FROM TRANSACTION_TABLE WHERE transactionDate >= :fromDate AND transactionDate <= :toDate AND staffId = :staffId")
LiveData<List<Transaction>> getTransactionSummaryByDates(Date fromDate, Date toDate, String staffId);
This is how I search for the transactions by dates
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartDate:
if(!hasSelectedStaffId) {
Toast.makeText(this, "Select a staff id first.", Toast.LENGTH_SHORT).show();
return;
}
Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
dpdStartDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
hasSelectedStartDate = true;
startDate = new Date(year, monthOfYear, dayOfMonth, 0, 0, 0);
btnStartDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
dpdStartDate.show();
break;
case R.id.btnEndDate:
cldr = Calendar.getInstance();
day = cldr.get(Calendar.DAY_OF_MONTH);
month = cldr.get(Calendar.MONTH);
year = cldr.get(Calendar.YEAR);
dpdEndDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
endDate = new Date(year, monthOfYear, dayOfMonth, 23, 59, 59);
btnEndDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
if (hasSelectedStartDate && hasSelectedStaffId) {
viewModel.getTransactions(startDate, endDate, selectedStaffId);
transactionAdapter.setTransactionList(transactionList);
transactionAdapter.notifyDataSetChanged();
}
}
}, year, month, day);
dpdEndDate.show();
break;
}
}
And this is in my viewmodel to get the transactions
public void getTransactions(Date startDate, Date endDate, String staffId) {
transactionList = transactionRepository.getTransactionSummaryByDates(startDate, endDate, staffId);
}
How come, I do not get any information from the database? If I check my database, the transactions are recorded. Please see image.
This is the parameters I send so I can get via dates
startDate: Wed Jan 25 00:00:00 GMT+08:00 3922
endDate: Thu Jan 26 23:59:59 GMT+08:00 3922
staffId: 10164
But if I convert my dates that I get from the datepicker to epoch like this:
if (hasSelectedStartDate && hasSelectedStaffId) {
Long lStartDate = startDate.getTime();
Long lEndDate = endDate.getTime();
viewModel.getTransactions(lStartDate, lEndDate, selectedStaffId);
//viewModel.getTransactions(startDate, endDate, selectedStaffId);
//setupTransactionList();
}
I've noticed that in my database, the date is 16431... But when I query and I convert my date parameters, it is 6060....
How do I make this right?
The mistake I had was in the codes of my onClick(View ...). I just converted my Date Pickers to Calendar and got the time from it like so..
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartDate:
if(!hasSelectedStaffId) {
Toast.makeText(this, "Select a staff id first.", Toast.LENGTH_SHORT).show();
return;
}
Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
dpdStartDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
hasSelectedStartDate = true;
cldr.set(year, monthOfYear, dayOfMonth, 23, 59, 59);
startDate = cldr.getTime(); //new Date(year, monthOfYear, dayOfMonth, 0, 0, 0);
btnStartDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
dpdStartDate.show();
break;
case R.id.btnEndDate:
if(!hasSelectedStaffId) {
Toast.makeText(this, "Select a staff id first.", Toast.LENGTH_LONG).show();
return;
}
if(!hasSelectedStartDate) {
Toast.makeText(this, "Select a start date first.", Toast.LENGTH_LONG).show();
return;
}
cldr = Calendar.getInstance();
day = cldr.get(Calendar.DAY_OF_MONTH);
month = cldr.get(Calendar.MONTH);
year = cldr.get(Calendar.YEAR);
dpdEndDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
cldr.set(year, monthOfYear, dayOfMonth, 23, 59, 59);
endDate = cldr.getTime();
btnEndDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
if (hasSelectedStartDate && hasSelectedStaffId) {
viewModel.getTransactions(startDate, endDate, selectedStaffId);
setupTransactionList();
}
}
}, year, month, day);
dpdEndDate.show();
break;
}
}
The endDate = new Date(year, monthOfYear, dayOfMonth, 23, 59, 59); had a different format so since I was using the "Calendar" instance when saving, I figured that it should have been a "Calendar" instance that I should be passing as parameters.

TimePickerDialog displaying time in 12 hour format

I followed a short YouTube tutorial about TimePickerDialog. Since the video is short, it does not show how to display selected time in a 12-hour format. I want to know how to display it to 12-hour format with PM and AM at the side of the selected time.
This is the code I followed from YT:
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
int hour = selectedHour;
int minute = selectedMinute;
String time = String.format(Locale.getDefault(), "%02d:%02d", hour, minute);
electionsText.setText("Registrations Will End On:\n" + date + "\n# " + time);
}
};
int style = AlertDialog.THEME_HOLO_LIGHT;
TimePickerDialog timePickerDialog = new TimePickerDialog(this, style, onTimeSetListener, hour, minute, false);
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("KK:mm a");
String currentTime = simpleDateFormat.format(c.getTime());
dateTimeSharedViewModel.setTime(currentTime);
}
java.time
Use the modern java.time classes defined in JSR 310 that years ago supplanted the terrible legacy classes Calendar, Date, SimpleDateFormat.
Generally best to let java.time automatically localize rather than hard-code a format.
LocalTime
.of( hour , minute )
.format(
DateTimeFormatter
.ofLocalizedTime( FormatStyle.SHORT )
.withLocale( Locale.US )
)
You have to replace true instead of false and you're done
final Calendar c = Calendar.getInstance();
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
TimePickerDialog.OnTimeSetListener onTimeSetListener = (timePicker, selectedHour, selectedMinute) -> {
int hour = selectedHour;
int minute = selectedMinute;
String time = String.format(Locale.getDefault(), "%02d:%02d", hour, minute);
electionsText.setText("Registrations Will End On:\n" + date + "\n# " + time);
};
TimePickerDialog timePickerDialog = new TimePickerDialog(this, onTimeSetListener, mHour, mMinute, true);
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();

period.getDays() return each time 0 in android

I try to get the correct difference time between the current day and second selected day from the calendar.
I'm using in this case LocalDate and the 3 methods getDays() getMonths() getYears() to get the day and the month also the year:
public int dateDiff(int year,int month,int day) {
final int Day = c.get(Calendar.DAY_OF_MONTH);
final int Month = c.get(Calendar.MONTH);
final int Year = c.get(Calendar.YEAR);
LocalDate localDate1 = LocalDate.of(year,month,day);
LocalDate localDate2 = LocalDate.of(Year,Month,Day);
Period period = Period.between(localDate2,localDate1);
int dayDiff = period.getDays();
return dayDiff;
}
public void onSelectedDayChange(#NonNull CalendarView view, final int year, final int month, final int dayOfMonth) {
textView.setText(""+dateDiff(year, month, day));
}
But each time when I test the code I got in the textView "0"
I try to see the value of the variable "period" and I got (P2M8D 'this result got in my example') that's mean the variable period count the difference between the days and the problem in the methods.
How can I solve this problem?
The problem in this project are in the name of variables, I'm using the same name of current time and the selected time I just change the first letter with capital one but this make problem.
That's why every time when i run the project i got 0
I change the program like that:
public int dateDiff(int year,int month,int day) {
final int dayOfToday = c.get(Calendar.DAY_OF_MONTH);
final int monthOfToday = c.get(Calendar.MONTH);
final int yearOfToday = c.get(Calendar.YEAR);
LocalDate localDate1 = LocalDate.of(year,month,day);
LocalDate localDate2 = LocalDate.of(Year,Month,Day);
Period period = Period.between(localDate2,localDate1);
int dayDiff = period.getDays();
return dayDiff;
}
Here, this should help.
public int dateDiff(int year,int month,int day) {
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,day);
thatDay.set(Calendar.MONTH,month); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, year);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
return days;
}

Get Date and Month by using a number in JAVA

I want to get the date and month by using a given number. How can I do that with calendar class easily?
example : 079 is march 19.
You need something like that:
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
localCalendar.set(Calendar.DAY_OF_YEAR, 79);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formatted = sdf.format(localCalendar.getTime());
System.out.println(formatted);
This will output "2015-03-20".
Try this is one :
// Get the year, month, day, hour, minute, second
import java.util.Calendar;
public class GetYMDHMS {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// You cannot use Date class to extract individual Date fields
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 to 11
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
System.out.printf("Now is %4d/%02d/%02d %02d:%02d:%02d\n", // Pad with zero
year, month+1, day, hour, minute, second);
}
}

how to get MONTHS, DAYS and weeks (android datepicker)

UPDATE
I am creating a pregnancy due date countdown, so I use android.widget.DatePicker as a tool to set the due date.
For example:
the set due date is Jan. 9 2015
the date now is Nov. 9 2014
so the left months, days and weeks is 2 months, 62 days and 8weeks
So far i can only display the set due date.
Question:
How to get the exact months weeks and days left when the user set the due date.
UPDATE CODE
Here's the code:
private TextView txtResultDueDate ;
private DatePicker datePicker;
private Calendar calendar;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
txtResultDueDate = (TextView) findViewById(R.id.txtDue);
btnChangeDate = (Button)findViewById(R.id.button1);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
Chronology chrono = GregorianChronology.getInstance();
DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);
DateTime current = new DateTime();
Interval interval = new Interval(current.toInstant(), end.toInstant());
Period duePeriod = interval.toPeriod();
showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());
}
};
private void showDate(int year, int month, int day) {
txtResultDueDate.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
This is the error that I encounter when I set the due date using DatePicker:
FATAL EXCEPTION: main
java.lang.IllegalArgumentException: The end instant must be greater orequal to the start
at org.joda.time.base.Abstraction.checkInterval(AbstractInterval.java.63)
at org.joda.time.base.BaseInterval(BaseInterval.java:94)
at org.joda.time.Interval.(Interval.java.122)
at com.date.androin.Profile$1.onDataset(Profile.java:168)
at android.app.DatePickerDialog.tryNotifyDataSet(DatePickerDialog.java.148)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java.116)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStrat.main(Native Method)
There is a library Joda Time. It is better the Date API provided by Java
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
Yes, you can use joda lib with android DatePicker
Chronology chrono = GregorianChronology.getInstance();
// end datetime
DateTime end = new DateTime(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 0, 0 ,chrono);
// current datetime
DateTime current = new DateTime();
Then instantiate Interval with start and end datetime
Interval interval = new Interval(current.toInstant(), end.toInstant());
then use the Interval api to get the Period from which you can extract the difference of months/days/weeks
Period duePeriod = interval.toPeriod();
// get difference in months
duePeriod.getMonths();
// get difference in weeks
duePeriod.getWeeks();
PLease refer the below Javadoc of Period for complete list of API
http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html
For Android, in your case add the above code into your DatePicker onDateSet listener. finally the listener method would like this,
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
// TODO Auto-generated method stub
Chronology chrono = GregorianChronology.getInstance();
// end datetime
DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);
// current datetime
DateTime current = new DateTime();
Interval interval = new Interval(current.toInstant(), end.toInstant());
Period duePeriod = interval.toPeriod();
showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());
}
//somewhere in your code, init part
Calendar then = setDate(9, 0, 2015);//9 january 2015
Calendar c = Calendar.getInstance();
Calendar now = setDate(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
String leftDays = getLeftDays(then, now);//your result
//method setting days months years - we ignore hours and minutes
private String getLeftDays(Calendar then, Calendar now) {
long leftMilis = then.getTimeInMillis() - now.getTimeInMillis();
int seconds = (int) (leftMilis / 1000);
Log.d(TAG, "seconds:" + seconds);
int minutes = seconds / 60;
Log.d(TAG, "minutes:" + minutes);
int hours = minutes / 60;
Log.d(TAG, "hours:" + hours);
int days = hours / 24;
Log.d(TAG, "days:" + days);
int weeks = days / 7;
Log.d(TAG, "weeks:" + weeks);
//months.. another way calculating data due not equal amount of days per month
Calendar temp = ((Calendar) then.clone());
temp.add(Calendar.MONTH, -now.get(Calendar.MONTH));
int months = temp.get(Calendar.MONTH);
Log.d(TAG, "months:" + months);
StringBuilder sb = new StringBuilder();
String format = "%d months, %d days, %d weeks";
String formatStr = String.format(format, months, days, weeks);
String result = sb.append(formatStr).toString();
Log.d(TAG, sb.toString());
return result;
}
private Calendar setDate(int day, int month, int year) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Log.d(TAG, c.getTime().toString());
return c;
}
Calendar c = calendar.getInstance();
and DatePickerDialog d
#Override
public void onDateSet(DatePicker view,int Year,int mont of Year,int day of month){
Toast
c.get(Calendar.Year),c.get(Calendar.Month),c.get(Calendar.Day_of_Month);
d.show
this code is to find week from selected date,it's proper work.
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(Integer.parseInt(selected_year), Integer.parseInt(selected_month), Integer.parseInt(selected_date)); // set date 1 (yyyy,mm,dd)
System.out.println("Selected Date==>>" + date1);
date2.clear();
date2.set(Integer.parseInt(current_year), Integer.parseInt(current_month), Integer.parseInt(current_date));
System.out.println("Current Date==>>" + date2);
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
week = (int) (dayCount / 7);
if (week <= 0) {
Toast.makeText(this, "Sry System Error", Toast.LENGTH_SHORT).show();
System.out.println("Week==>>" + week);
test = false;
} else {
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
System.out.println("Week==>>" + week);
test = true;
}

Categories