java.text.ParseException: Unparseable date: "26/4/2016" (at offset 0) - android

I have two textview, I am using separate datepicker on textview's onclick listener,I am trying to get difference between selected dates,but I am getting following error
java.text.ParseException: Unparseable date: "26/4/2016" (at offset 0)
on this line
Date past = format.parse(enddt);
Following is my code can any one help me with that
startdates=(TextView)findViewById(R.id.activity_entry_startdate);
startdates.setOnClickListener(this);
enddates=(TextView)findViewById(R.id.activity_entry_enddate);
enddates.setOnClickListener(this);
Like this way i am opening datepickers
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
startc = Calendar.getInstance();
int year = startc.get(Calendar.YEAR);
int month = startc.get(Calendar.MONTH);
int day = startc.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
//dialog.getDatePicker().setMaxDate(new Date().getTime());
dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
return dialog;
//return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
startdates.setText(String.valueOf(day) + "/" + String.valueOf(month + 1) + "/" + String.valueOf(year));
Log.d("month", String.valueOf(year));
}
}
public static class DatePickerFragments extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
endc = Calendar.getInstance();
int year = endc.get(Calendar.YEAR);
int month = endc.get(Calendar.MONTH);
int day = endc.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
return dialog;
//return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
enddates.setText(String.valueOf(day) + "/" + String.valueOf(month + 1) + "/" + String.valueOf(year));
Log.d("month", String.valueOf(year));
difs();
}
}
public static void difs()
{
try {
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
String enddt= String.valueOf(format.parse(enddates.getText().toString()));
Date past = format.parse(enddt);
Date now = new Date();
System.out.println(TimeUnit.MILLISECONDS.toMillis(now.getTime() - past.getTime()) + " milliseconds ago");
System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");
}
catch (Exception j){
j.printStackTrace();
}
}

your Dateformat is not correct so change the code like this
DateFormat df = new SimpleDateFormat("MM/dd/yyyy",Locale.ENGLISH);
Date past = df.parse(enddt);

Your format is new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH), but your date is 26/4/2016 which is totally different from your SimpleDateFormat.
Use "dd/MM/yyyy" instead of "EE MMM dd HH:mm:ss z yyyy"

You have to change the SimpleDateFormat string in your difs() method. And be sure to use the right one, as some showed here with MMfor the month is not absolutely correct in your case. If you have a date like 26/4/2016, you just have to use one M:
public static void difs()
{
try {
//change here to dd/M/yyyy for a date like 26/4/2016
SimpleDateFormat format = new SimpleDateFormat("dd/M/yyyy",
Locale.ENGLISH);
String enddt= String.valueOf(format.parse(enddates.getText().toString()));
Date past = format.parse(enddt);
Date now = new Date();
System.out.println(TimeUnit.MILLISECONDS.toMillis(now.getTime() - past.getTime()) + " milliseconds ago");
System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");
}
catch (Exception j){
j.printStackTrace();
}
}
EDIT:
Your question and your comments are a little bit confusing and different. For explanation, if you have a SimpleDateFormat string like:
Tue Apr 26 00:00:00 EDT 2016
Your SimpleDateFormat must look like:
SimpleDateFormat format = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyyy",Locale.ENGLISH);
That means that you have to give the exact String to parse that matches to the SimpleDateFormat. In other words, an example to pass the correct String would be:
Date past = format.parse("Tue Apr 26 01:20:56 EDT 2016");
And if you want to grab a date string like
26/4/2016
Your SimpleDateFormat must look like:
SimpleDateFormat format = new SimpleDateFormat("dd/M/yyyy",
Locale.ENGLISH);
and the String that should be formated must look like this:
Date past = format.parse("26/4/2016");
And so on...as nobody here can exactly know what String you are passing, I recommend to read the Documentation about SimpleDateFormat. It´s one of the easy described and understandable parts of the API:
http://developer.android.com/reference/java/text/SimpleDateFormat.html

Related

calendar timeinmillis returns wrong value

With a DatePicker I choose a Date and I need the date and the timestamp
from the chosen date:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Ctag = sdf.format(calendar.getTime()).substring(0,3)+".";
CdTag = String.format("%02d",dayOfMonth);
Cmonat = String.format("%02d",monthOfYear+1);
Cjahr = Integer.toString(year);
Cdatum = CdTag+"."+Cmonat+"."+Cjahr;
Ctimestamp = (int) (long) calendar.getTimeInMillis();
getDatum.setText(Ctag+","+CdTag+"."+Cmonat+"."+Cjahr);
Snackbar snackbar = Snackbar.make(cl_main,String.valueOf(Long.valueOf(calendar.getTimeInMillis()).intValue()),3000).setDuration(Snackbar.LENGTH_INDEFINITE);
snackbar.show();
}
};
So I set the date which is picked and calendar.getTimeInMillis() I want the timestamp from the date.
But for example I choose today 18.04.2019 it returns 843974600
and when I convert it on a UNIX convert website it gives me
following date:
GMT: Sunday, 29. September 1996 05:23:20
Your time zone: Sonntag, 29. September 1996 07:23:20 GMT+02:00 DST
Relative: 23 years ago
You can try with this code, it should work :
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
Long timeinmilli = calendar.getTimeInMillis(); //will give tou time in ms
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //format of the date, choose what you want
Date resultdate = new Date(timeinmilli); //create an object date associated to the time in ms
String date = DateFormat.format(resultdate).toString(); //convert the date into a string with the format you choose

how to set current Date as MinDate in DatePickerDialog

I have one activity that i use to create customer, in this activity i have one edit text that can show the current date when user open screen. its can be change to future date but not past date so i have used
d2.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
to set current date as a minimum date and onClick i have opening DatePickerDialog. But, when click on that edit text app is crashed and this error show in Logcat.
java.lang.IllegalArgumentException: fromDate: Wed Aug 22 16:31:24
GMT+05:30 2018 does not precede toDate: Wed Aug 22 00:00:00 GMT+05:30
2018
here is my edittext onClickListner code.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.dateFormatForDOB);
try {
cal.setTime(sdf.parse(edt.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
DatePickerDialog d2 = new DatePickerDialog(CreateUpdateOpportunityActivity.this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int years,
int monthOfYear, int dayOfMonth) {
year = years;
month = monthOfYear;
day = dayOfMonth;
tv.setText(DateUtil.getDateOfBirth(year + "-" + (month + 1) + "-" + day));
}
}, year, month, day);
d2.getDatePicker().setSpinnersShown(true);
d2.getDatePicker().setCalendarViewShown(false);
d2.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
d2.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
d2.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
d2.show();
d2.setCanceledOnTouchOutside(false);
i used other solution like
d2.getDatePicker().setMinDate(System.currentTimeMillis());
or
d2.getDatePicker().setMinDate(new Date().getTime() - 10000);
but still app crash and same error comes
if i comment above line of code, my app run without crash.
you need to check if calendar date(cal.getTimeInMillis()) is greeter then your current date(System.currentTimeMillis())
like this
if (cal.getTimeInMillis() < System.currentTimeMillis()) {
// Toast.makeText(getApplicationContext(),"Current time is big",Toast.LENGTH_SHORT).show();
d2.getDatePicker().setMinDate(cal.getTimeInMillis());
} else {
// Toast.makeText(getApplicationContext(),"Current time is small",Toast.LENGTH_SHORT).show();
d2.getDatePicker().setMinDate(System.currentTimeMillis());
}
may be this help

Date and time format in Android

How do you format correctly according to the device configuration a date and time when having year, month, day, hour and minute? for example I want to display 29 July, 2015, 10:30 Am, according to my time zone
You can use this method to format the datetime... u can replace new java.util.Date() with any datetime variable...
android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("dd-MMM-yyyy hh:mm aa", new java.util.Date());
String strDateTime = "29 July, 2015, 10:30 Am";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM, yyyy, hh:mm a");
strDateTime = sdf.format(Calendar.getInstance().getTime());
holder.txtTime.setText(strDateTime);
Please integrate the above code, that works fine for me.
Any help, do let me know.
Please Find the below solution
Calendar ci = Calendar.getInstance();
String AM_PM;
if(ci.get(Calendar.AM_PM)==0)
{
AM_PM ="AM";
}
else
{
AM_PM ="PM";
}
String CiDateTime = "" + ci.get(Calendar.DAY_OF_MONTH)+" "+
(ci.get(Calendar.MONTH) + 1)+","+
ci.get(Calendar.YEAR) + "-" +
+ "," +getCurrentTime()
+" "+AM_PM;
Call the method
private String getCurrentTime()
{
int hrsRight = 0;
Calendar c = Calendar.getInstance();
int hrs = c.get(Calendar.HOUR);
int min = c.get(Calendar.MINUTE);
if (hrs>12)
{
hrsRight = hrs - 12;
}
else
{
hrsRight = hrs;
}
return String.valueOf(hrsRight)+":"+String.valueOf(min);
}

DatePickeDialog displays one month greater in android

When i press the button to display the DatePickerDialog, the dialog displays one month greater. For instance, if i initiate with the current date like this(with the DateTime of joda library):
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
which is 07/08/2014, the date dialog displays one month greater 07/09/2014.
I do not understand why this happens.
The fragment which represents the datePickerFragment is:
#SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#SuppressLint("ValidFragment")
TextView txtDate;
GlobalData appState;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
Log.i("DatePickerFragment day month year", day +" "+ month + " "+ year + "");
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
appState.setDateUserFrom(year, month, day);
Log.i("Date day month yerar", "Date changed." + day+" " + month + " " +year);
txtDate.setText(new StringBuilder().append(day)
.append("-").append(month).append("-").append(year)
.append(" "));
}
}
DatePickerDialog takes monthOfYear that is 0 to 11 [0 for Jan... 11 for Dec], and your DateTime returns 1 to 12. So you need to do -1 with month value.
Use this:
return new DatePickerDialog(getActivity(), this, year, month - 1, day);
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear()-1;
int day = dt.getDayOfMonth();
Log.i("DatePickerFragment day month year", day +" "+ month + " "+ year + "");
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
Month in date picker starts with zero. So you should subtract one from the getMonthOfYear() to set it on datepicker.
I am pretty sure the reason behind this is because the Android DatePickerDialog expects 0 based month values. Jodatime return them as you would expect it (more human friendly). So just subtract 1 from the month.
Just to clarify, most date functions/libraries are designed with 0 based month values by default. The exception is where explicitly noted, or third party libraries like Jodatime, which make working with date stuff a joy.
Just a guess. Joda month starts at 1 for january but java date at 0? So if you use the current date init with joda the date picker will show the wrong month. Easy solution:
month = dt.getMonthOfYear() - 1;
Try this hope it's worked:
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonth();
int day = dt.getDayOfMonth();
OR
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear() - 1;
int day = dt.getDayOfMonth();

How to get day, month and year from DatePickerDialog?

I'd like to get day, month and year values for save to db. These are my codes:
Declaretions:
private TextView tv_purchase_date;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
OnClickListener listener_show_dlg = null;
OnDateSetListener listener_mdate_display = null;
Event Code:
listener_show_dlg = new OnClickListener() {
public void onClick(View v) {
Calendar cal=Calendar.getInstance();
DatePickerDialog datePickDlg = new DatePickerDialog(
ItemsAddActivity.this,
listener_mdate_display,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
);
datePickDlg.show();
};
};
listener_mdate_display = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mMonth = month;
mYear = year;
mDay = dayofMonth;
tv_purchase_date.setText(dayOfMonth + "/" + monthOfYear + "/" + year);
}
};
}
I try to store mMonth, mYear and mDay values in db. What is the best store type? as integer or as string??
I store in the DB one number that represents the date. It is the number of seconds that have passed since the beginning of the modern era (Jan 1, 1970.) From the Date Picker, you can get the M D Y values like this:
datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int yearOfYear,
int monthOfYear, int dayOfMonth) {
// the user has picked these values
year = yearOfYear;
month = monthOfYear;
day = dayOfMonth;
Then, I turn these into a single Date object like this.
Calendar cal = new GregorianCalendar(year, month, day);
Date dateOfGames = cal.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
String cs = df.format(dateOfGames);
changeDateButton.setText(cs); // update the interface
}
};
before I put it in the DB, I turn it into a numebr of seconds like this:
long seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
....
when I take that single number of seconds out of the DB, and want it to be a Date object again, I do this:
date = new Date(seconds * 1000); // converting seconds to a Date object
You can use a DateFormat object to display the date object how you like to see it.
I know this is awkward. Since SQLite doesn't allow you to store a Date, the answer is going to be awkward. Perhaps there is a cleaner way than this, and others will recommned something. :)
I struggled with this issue for a while. I don't konw of anything better than this.
I stored the date in the DB as a single long int. It is pretty easy to convert your Date to the number of seconds since the epoch (Jan 1, 1970), and it is also easy to convert the number of seconds into a Date object.
You need to be careful with seconds and milliseconds.
date = new Date(seconds * 1000); // converting seconds to a Date
seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
// Use Greg calendar to get a Date object from day, month, year
Date dateOfGames = new GregorianCalendar(year, month, day).getTime();
Does that help at all?
I created sqllite table with this sql string:
create table items (id INTEGER PRIMARY KEY AUTOINCREMENT, pdate DATE)
I writed some methods to convert date:
public String date_to_str(Date date) {
String pattern = "dd.MM.yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Log.d(_watcher_name, "date_to_str" + dateFormat.format(date));
return dateFormat.format(date);
}
public Date mdy_to_date (int day, int month, int year) {
Calendar cal = new GregorianCalendar(year, month, day);
return cal.getTime();
}

Categories

Resources