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.
Related
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
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
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
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;
}
ANDROID:
Wanted to know whether is there any API or workaround to know that DAY X + N DAYS ahead or behind was the day that will be / was of next month / previous month.
public static Date getCurrentDatePlusDays(int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_YEAR, days);
Date newDate = calendar.getTime();
return newDate;
}
then check the month or year.