I am trying to convert a date from date picker to get number of days in Android.
For example if I choose 19/11/2015, the number of days should be 2 days. I need to find a solution for this as it is important for my project. There are many solutions on the web for getting the number of days between two dates but not from a single date. Can anyone help please?
Below is the method where I have to set and convert the date.
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = +dayOfMonth+"/"+(++monthOfYear)+"/"+year;
Calendar end = Calendar.getInstance();
end.set(year, monthOfYear, dayOfMonth);
long timenow= System.currentTimeMillis();
long endDate = end.getTimeInMillis();
long diffTime = endDate - timenow;
days = (int) (diffTime / (1000 * 60 * 60 * 24));
DateFormat dateFormat = DateFormat.getDateInstance();
dateFormat.format(endDate);
//System.out.println(diffDays);
dateTextView.setText(Integer.toString(days));
Answer for:
Right now it is giving me this bug
The reason for the error is you are trying to set an int as value to dateTextView.
Instead of dateTextView.setText(days); try dateTextView.setText(Integer.toString(days));
Related
i want to compare a date with the current date and do something if the difference is 2 months or 6 or a year .. but i have a problem how to get the correct difference for example if the current month is 02 2015 and the other month is 10 2014 i will get 8 in difference but the actual difference is 4 .. how to do it ?
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat d = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");
SimpleDateFormat ye = new SimpleDateFormat("yyyy");
String day = d.format(c.getTime());
String month = m.format(c.getTime());
String year = ye.format(c.getTime());
int d1=Integer.parseInt(day);
int m1=Integer.parseInt(month);
int d2=25;
int m2=02;
int diff=d1-d2;
String s=String.valueOf(diff);
You are calculating your difference between two int, so it can't work.
You should calculate it between two dates or two long (in secondes or milliseconds)
long oneDay, today, delay;
oneDay = 1000*3600*24; //number of milliseconds in a day
today = Calendar.getInstance().getTimeInMillis();
delay = (TheDateYouWantToCompare - today)/oneDay;
if (delay >= 60*oneDay) { //more than 2 months
//your code
}else{
//your code
}
If TheDateYouWantToCompare and today are dates, it's almost the same :
delay = (TheDateYouWantToCompare.getTime() - today.getTime())/oneDay;
Edit :
Here it is how to get time in milliseconds.
String DateString = "31-12-2015";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = sdf.parse(DateString);
long timeInMilliseconds = myDate.getTime();
You could just use the difference in milliseconds between the 2 dates. Pre-compute the differences you need/want as constants and compare to the delta you have, for example:
static final long DAY = 1000 * 60 * 60 * 25;
static final long MONTH = DAY * 30;
...
int diff = d1 - d2;
if(diff > MONTH) {
//more than a month difference
}
If you need something more complex you should perhaps use a library such as Joda Time which will give a more comprehensive set of features to work with time.
My code to calculate remaining days for next birthday gives me following error when I use leap year i.e.; when used with 29th feb
*ERROR**Value 29 for dayOfMonth must be in the range [1,28]
Please help me in this problem...
public int getDaysRemainingForNextBirthDay(){
Calendar cal=Calendar.getInstance();
int currentYear=cal.get(Calendar.YEAR);
int currentMonth=cal.get(Calendar.MONTH);
int birthYear=currentYear;
int birthMonth=Integer.parseInt(m);
int birthDay=Integer.parseInt(d);
if (birthMonth<currentMonth) {
birthYear=birthYear+1;
}
DateTime birthDate=new DateTime(birthYear,birthMonth,birthDay,0, 0);
DateTime currentDate=DateTime.now();
Period datePeriod=new Period(currentDate,birthDate,PeriodType.days());
PeriodFormatter periodFormatter=new PeriodFormatterBuilder()
.appendDays().appendSuffix("").toFormatter();
return Integer.parseInt(periodFormatter.print(datePeriod));
}
The problem is that in Java's Calendar the months are numbered from 0, but in Joda Time they are numbered from 1.
So in your example you pass 2 as the month, which is March according to the Calendar class, but it is interpreted as February by the Joda Time framework.
To solve it just add 1 to the month you get from Calendar when passing it to Joda.
I want to save system date on my database, but it returns : 22/0/2013.
here my code :
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month_ = cal.get(Calendar.MONTH);
int day_ = cal.get(Calendar.DATE);
String FullDate = (""+day_+"/"+month_+"/"+year);
String text_Rate=(String.valueOf(FullDate));
Log.d("System Date show", text_Rate);
where i'm doing wrong.
This is the correct behavior. The Java Calendar month is 0-based (January is 0, December is 11).
If you really want to store it as 22/1/2013, simply add +1 to your month:
int month_ = cal.get(Calendar.MONTH) + 1;
you should save dates as long to sqlite. that is easier and less prone to errors. see here for calendar to long.
I am getting date and time from DatePicker and TimePicker like:
int dateofmonth = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();
int hour = time.getCurrentHour();
int minutes = time.getCurrentMinute();
But i want date and time like this format:
Friday, December 14,2012 - 4:30 PM.
Any help?
formate it as you want ....
public void SetMyCustomFormat()
{
// Set the Format type and the CustomFormat string.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "put your formate here ";
}
for more help
http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.customformat.aspx
You could try to use SimpleDateFormat, see SimpleDateFormat
Under the examples section is a date that represents your required format.
You need to create a Date Object first from Calendar, you can do as below:
Calendar cal= Calendar.getInstance();
cal.setTime(new Date());
int dateofmonth = date.getDayOfMonth();
int month = date.getMonth();
int year = date.getYear();
cal.set(dateofmonth, month, year);
Now create a SimpleDateFormat object, with the format, you desire, and format date with that format, by
String formattedDate=simpleDateFormat.format(cal.getTime());
If all you need is formatting a Date object in the current locale, you can use DateFormat:
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, picker.getYear());
...
String str = DateFormat.getDateTimeInstance().format(date);
The method getDateTimeInstance() returns the preferred display for the current locale, which is desirable to internationalize your application because different locales have different preferences for the order of the components. For example:
US: Friday, December 14,2012 - 4:30 PM
Italy: Venerdì 14 Dicembre 2012, 16:30
I'm trying to generate a random month and year with an upper bound of the current year and month and a lower bound that will be a static month and year.
I can generate the year with:
int randomYear = (int) (Math.random() * ( currentYear - 2000 ))+2000;
//returns a val 2000-2012
Where 2000 is my lower bound. So hypothetically that would generate a year between 2012-2000. The problem I run into is when I try to set a month I'm not sure how to handle if the random generator returns 2012 and there is only 2 months. Currently I have:
int randomMonth = (int) Math.random() * (12);
How do I handle the special cases such as the case with 2012 or if I set the lower bounds for a year 2000 and a month of 10?
This might seems a little bit long to you, but it's much nicer to work with actual dates:
public static void main(String[] args) {
Calendar now = Calendar.getInstance();
Calendar min = Calendar.getInstance();
Calendar randomDate = (Calendar) now.clone();
int minYear = 2012;
int minMonth = 2;
int minDay = 18;
min.set(minYear, minMonth-1, minDay);
int numberOfDaysToAdd = (int) (Math.random() * (daysBetween(min, now) + 1));
randomDate.add(Calendar.DAY_OF_YEAR, -numberOfDaysToAdd);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(dateFormat.format(now.getTime()));
System.out.println(dateFormat.format(min.getTime()));
System.out.println(dateFormat.format(randomDate.getTime()));
}
public static int daysBetween(Calendar from, Calendar to) {
Calendar date = (Calendar) from.clone();
int daysBetween = 0;
while (date.before(to)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
System.out.println(daysBetween);
return daysBetween;
}
//edit: puh.. harder than I thought ;) But that's it.
Why not use unix timestamps - find the current time as a timestamp and the start time as a timestamp.
Now you have two integers, and it'll be easy to pick a random integer between them and convert it back into a proper date/time.