date retreival in android - android

In my application i have 2 field, 1 is date and another is recc(is an integer) in database table.
Now i will explain my requirement:
Consider suppose user enters today's date(26-07-2012) and recc as 10.It means that starting from today's date to that +10 date.I got that 10th date from today's date.But what i want is 10th day from today's date means it will surely go to next month also (26-07-2012----5-08-2012),but i have to know the count of date which falls in this particular month,(i.e)between 26-07-2012----5-08-2012 how many days it will fall within this month.I think i have explained my problem clearly,if not i am ready to give more explanation.Thanks in advance.
Date value:
EditText date=(EditText)findViewById(R.id.startdateexp);
String startdate=date.getText().toString();

you can do this by following way:
1. Get date from Database.
Now get day of month from the date by following method:
DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = iso8601Format.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing ISO8601 datetime failed", e);
}
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int currentDay= cal.get(Calendar.DAY_OF_MONTH);
calculate Last day of month by:
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

If you're using the Date class you can offset it by the number of days converted to milliseconds to create a new Date:
Date datePlusRecc = new Date(oldDate.getTime() + recc*86400000); // 86400000 = 24*60*60*1000
Note that this is useable only when recc is relatively small (< about 20), because otherwise the multiplication will overflow.

Just use the java.util.Date class combined with your date in milliseconds.
In a for loop add one day to the one version in milliseconds and convert it back to Date. Get the Month out of the Date Object and compare it with the current month. As soon as the month is a new one you have your total count of days in the current month.
Date currentDate = new Date(currentMillis);
long countingMillis = currentMillis;
int daysInSameMonth = 0;
while(true){
daysInSameMonth++; // if the actual date schould not count move this line at the button of the while
countingMillis += 1000*60*60*24;
Date dt = new Date(countingMillis);
if(currentDate.getMonth() != dt.getMonth())
break;
}

Related

get start and end date of the week

Actually i want to display a set of data with the start and end date of the week were that particular date falls on. In my emulator its working fine. Eg. If i give Apr 23 its giving me start date of the week as 22 Apr and end date as 28 Apr, but if i try to build the same code in my device its showing start date of the week as 27 Apr and end date as 28 Apr.
Piece of Code which i am using:
//to get first day of week
cal1.set(Calendar.DAY_OF_WEEK, 1);
int day1 = cal1.get(Calendar.DAY_OF_MONTH);
//to get last day of week
cal1.set(Calendar.DAY_OF_WEEK, 7);
int day7 = cal1.get(Calendar.DAY_OF_MONTH);
I don't know why you getting that data but this is how I get the first and last date, take look might help. (its written to give current week's first and last date, so might have to tweak it little bit.)
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime();
//current date to check that our week lies in same month or not
SimpleDateFormat checkformate = new SimpleDateFormat("MM/yyyy");
String currentCheckdate= checkformate.format(date1);
int weekn = calendar.get(Calendar.WEEK_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
//resat calender without date
calendar.clear();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.WEEK_OF_MONTH,weekn);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.YEAR,year);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date datef = calendar.getTime();
//move date to 6 days + to get last date of week
Long timeSixDayPlus = calendar.getTimeInMillis()+518400000L;
Date dateL = new Date(timeSixDayPlus);
String firtdate = simpleDateFormat.format(datef);
String lastdate = simpleDateFormat.format(dateL);
String firtdateCheck = checkformate.format(datef);
String lastdateCheck = checkformate.format(dateL);
//if our week lies in two different months then we show only current month week part only
if (!firtdateCheck.toString().equalsIgnoreCase(currentCheckdate)) {
firtdate = "1" + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR);
}
if (!lastdateCheck.toString().equalsIgnoreCase(currentCheckdate)) {
int ma = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
lastdate = String.valueOf(ma) + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR);
}
Log.e("current","=>>"+firtdate+" to "+lastdate);
To get the first day of the week -
initialize the Calendar as per your need. in this case, I am getting the current date calendar.
set the current day of the week to the first day of the week.
get the corresponding date.
Calendar calendar = Calendar.getInstance();
//optional step
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
int firstDateOfWeek = calendar.get(Calendar.DATE);
To get the last date of the week -
follow the step as above to initialize.
set the day of the week as Saturday.
get the corresponding date.
Calendar calendar = Calendar.getInstance();
//optional step
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
int lastDateOfWeek = calendar.get(Calendar.DATE);
In this way, you can get eh first and the last date for the week. one thing to keep in mind that I have set the first day of the week as SUNDAY. set as per your need. although it is purely optional to set the first day of the week. this gives you a more transparency in code.

Same Milliseconds values coming for different dates

I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.

Android converting calendar in one TimeZone to local TimeZone

I am using following code to convert timezone (GMT-3) to device local timezone.
int hour=17,minute=0,day=12,month=6,year=2014;
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-3"));
cal.set(year, (month-1), day,hour,minute);
cal.setTimeZone(TimeZone.getDefault());
Log.d("Time", cal.get(Calendar.DATE)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR)+" , "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+" "+cal.get(Calendar.AM_PM));
My local timezone is GMT+5:30
Expected result is
Time 13/5/2014, 1:30 0
But I am getting the result
12/5/2014 , 13:30 1
Sorry for you, GregorianCalendar is sometimes the hell. Your problem is following:
If you immediately set the timezone after having set the fields for year, month etc. then this mutable calendar class will only shift the timezone retaining the already set fields containing the local time. Those fields for year, month etc. will NOT be recalculated. This behaviour causes a shift on the global timeline represented by cal.getTime(), too.
In order to force the calendar object to recalculate the fields you need to call a getter. Watch out for following code and especially remove the comment marks to see the effect.
int hour = 17, minute = 0, day = 12, month = 6, year = 2014;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
TimeZone tz1 = TimeZone.getTimeZone("GMT-3");
sdf.setTimeZone(tz1);
Calendar cal = new GregorianCalendar(tz1);
cal.set(year, (month - 1), day, hour, minute);
// System.out.println(sdf.format(cal.getTime()));
// System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
TimeZone tz2 = TimeZone.getTimeZone("GMT+0530");
sdf.setTimeZone(tz2);
cal.setTimeZone(tz2);
System.out.println(sdf.format(cal.getTime()));
System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
Output with comment-disabled lines:
2014-06-12T17:00+0530
Hour=17
Output with enabled lines after having removed the comment marks:
2014-06-12T17:00-0300
Hour=17
2014-06-13T01:30+0530
Hour=1

How to get First Day and last day of the week of a date

I am using DatePickerDialog to show the calender. I want to access First day and last day of the week of the date selected.
Here is what I have tried
this.tv_date.setText( new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("-")
.append(monthName).append("-")
.append(mYear).append(""));
tv_date.setHighlightColor(Color.CYAN);
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
sdf.format(""+str); //here I am getting exception
Calendar cal=Calendar.getInstance();
int s= cal.getFirstDayOfWeek();
Toast.makeText(getApplicationContext(), "first day of the week : "+s, 1).show();
But I am getting "IllegalArguementException".
Please help me
Thanks
sdf.format(""+str); - is wrong. You either need to pass a Date object to it, or else, change it to sdf.parse(str); to get a Date object from it.
Edit:- To get the first day of the week, do this.
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date();
try{
myDate = sdf.parse(str);
}catch(ParseException pe){
// Do Something
}
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.set(Calendar.DAY_OF_WEEK, 1);
int s = cal.get(Calendar.DATE);
Here is an example of calculating the first day of week.
private void firstDayOfThisWeek(){
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime firstDayThisWeek = today; //start value
int todaysWeekday = today.getWeekDay();
int SUNDAY = 1;
if(todaysWeekday > SUNDAY){
int numDaysFromSunday = todaysWeekday - SUNDAY;
firstDayThisWeek = today.minusDays(numDaysFromSunday);
}
System.out.println("The first day of this week is : " + firstDayThisWeek);
}
Instead of assigning today you can assign any other day with exact format

Getting number of days difference between 2 dates

I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".
1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?
2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10.
Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.
How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.
Thanks in advance
Omkar Ghaisas
To parse your date from text format:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");
More info : SimpleDateFormat doc
To substract days from your date:
public static Date substractDays(Date date, int days)
{
long millis = date.getTime();
long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
// 1milli 1s 1m 1h 1d
return new Date(millis-toSubstract);
}
Adding some days would be the same, except replace - with +
To get back a String representation from a Date object:
DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());
EDIT:
You could also do the Date adding/substracting with the method you suggested:
public static Date substractDays(Date date, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -20 /*or +10*/);
return calendar.getTime();
}
If you want to check if a Date is in an interval, then:
public static boolean isInInterval(Date date, Date from, Date to)
{
return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}

Categories

Resources