Making a calendar with a GridView - java

I have some code that I made to display a calendar using a GridView and I want to know if there is either an easier method of making a calendar, or if there is a way that I can change the appearance of a single item in the GridView for the current day. Code is below.
TextView tvMonth;
GridView gvCal;
DateFormat dateFormat;
Date date;
public static String[] days;
public static int[] months = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int today, beginOfMonth;
String month, year;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calender);
gvCal = (GridView) findViewById(R.id.gridView);
dateFormat = new SimpleDateFormat("yyyy");
date = new Date();
months[1] = Feb(Integer.parseInt(dateFormat.format(date))); // Find the amount of days in Feb
dateFormat = new SimpleDateFormat("MM");
int numDays = months[Integer.parseInt(dateFormat.format(date))-1] + 6; // Number of days in the month as well as making sure not to override the day names
// Check which day of the month the month started on. Eg: April 1st 2016 is a Friday
dateFormat = new SimpleDateFormat("MM");
month = dateFormat.format(date);
dateFormat = new SimpleDateFormat("yyyy");
year = dateFormat.format(date);
try {
beginOfMonth = (Day("01"+month+year))-1; // Get the beginning of the month (-1 because Android recognizes Sunday as the first day)
} catch (ParseException pe) {
Toast.makeText(getApplicationContext(), pe.getMessage(), Toast.LENGTH_LONG).show();
}
if (beginOfMonth == 0) {
beginOfMonth = 7;
}
days = new String[numDays+beginOfMonth];
days[0] = "Mon";
days[1] = "Tue";
days[2] = "Wed";
days[3] = "Thu";
days[4] = "Fri";
days[5] = "Sat";
days[6] = "Sun";
dateFormat = new SimpleDateFormat("dd");
String temp = dateFormat.format(date);
today = Integer.parseInt(temp);
if(beginOfMonth != 0) {
for (int i = 7; i <= (5 + beginOfMonth); i++) {
days[i] = "";
}
}
for (int i = (6 + beginOfMonth); i <= (days.length-1); i++) {
days[i] = Integer.toString(i-beginOfMonth-5);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.cal_days, days);
gvCal.setAdapter(adapter);
gvCal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
tvMonth = (TextView) findViewById(R.id.textView);
dateFormat = new SimpleDateFormat("MMMM"); // Get month name
tvMonth.setText(dateFormat.format(date));
}
public int Feb(int year) {
int temp;
try {
temp = year / 4;
} catch (Exception e) {
return 28;
}
return 29;
}
public int Day(String day) throws ParseException {
DateFormat df = new SimpleDateFormat("ddMMyyyy");
try {
Date d = df.parse(String.valueOf(day));
Calendar c = Calendar.getInstance();
c.setTime(d);
return c.get(Calendar.DAY_OF_WEEK);
} catch (Exception e) {
ParseException pe = new ParseException("There was a problem getting the date.", 0);
throw pe;
}
}

"I want to know if there is either and easier method of making a calendar, or if there is a way that I can change the appearance of a single item in the GridView for the current day."
Check this library: https://github.com/SundeepK/CompactCalendarView
You can add events to a date that will be shown as a tiny cycle under the number of day.

Related

how to highlights specific dates in CalendarView in android studio?

i have tried most things online from custom calendar views to dependencies but they all lead to being outdated and not usable for android studio in its latest version.
does anyone know how to achieve this? I have tried mCalendarView, SunDeepK CalendarView and material-calendar view, but to no avail..
private void setCustomResourceForDates() {
Calendar cal = Calendar.getInstance();
//highlighlighting the holidays in a month taking the static dates
ArrayList<String> dates = new ArrayList<String>();
dates.add("02-08-2015");
dates.add("22-08-2015");
dates.add("17-09-2015");
dates.add("25-09-2015");
dates.add("27-09-2015");
dates.add("13-10-2015");
dates.add("22-10-2015");
SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
for (int i = 1; i < dates.size(); i++) {
inputString2 = dates.get(i);
inputString1 = myFormat.format(date);
try {
//Converting String format to date format
date1 = myFormat.parse(inputString1);
date2 = myFormat.parse(inputString2);
//Calculating number of days from two dates
long diff = date2.getTime() - date1.getTime();
long datee = diff / (1000 * 60 * 60 * 24);
//Converting long type to int type
day = (int) datee;
} catch (ParseException e) {
e.printStackTrace();
}
cal = Calendar.getInstance();
cal.add(Calendar.DATE, day);
holidayDay = cal.getTime();
colors();
}
}
public void colors() {
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.green,
holidayDay);
caldroidFragment.setTextColorForDate(R.color.white, holidayDay);
}
}
}
call setCustomResourceForDates(); on onCreate method (in Caldroid Calendar
you can find it here : https://stackoverflow.com/a/32601769/20137896

How to get first and last date of weeks on basis of month and year in android

how to get first and last date of weeks on basis of month and year in android
ex:we pass month and year (March,2016) then i want all weeks just like
mar5- mar11,(sat to fri)
mar12- mar18,
mar19- mar25,
mar26-april01
please help me
Call this function to get results in a valid week pair list of given month of a year.
ex: getWeekStartEnd("December","2016");
Result: [
December3-December9,
December10-December16,
December17-December23,
December24-December30
]
List<String> getWeekStartEnd (String month , String year) {
List<String> validWeekPairs = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMMM-yyyy");
String day = "01";
try {
Date date = sdf.parse(day + "-" + month + "-" + year);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.SATURDAY);
List<String> startDayOfWeek = new ArrayList<>();
List<String> endDayOfWeek = new ArrayList<>();
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
boolean isStartDaySet = false;
boolean hasLastDayOfWeek = true;
for (int currentDay = 01; currentDay <= daysInMonth; currentDay++) {
Date newDate = sdf.parse(currentDay + "-" + month + "-" + year);
calendar.setTime(newDate);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY) {
if (hasLastDayOfWeek) {
startDayOfWeek.add(month + String.valueOf(currentDay));
isStartDaySet = true;
hasLastDayOfWeek = false;
}
} else if (dayOfWeek == Calendar.FRIDAY) {
if (isStartDaySet) {
endDayOfWeek.add(month + String.valueOf(currentDay));
hasLastDayOfWeek = true;
}
}
}
for (int i = 0; i < endDayOfWeek.size(); i++) {
validWeekPairs.add(startDayOfWeek.get(i) + "-" + endDayOfWeek.get(i));
}
return validWeekPairs;
} catch (ParseException e) {
e.printStackTrace();
return validWeekPairs;
}catch (Exception e){
e.printStackTrace();
return validWeekPairs;
}
}
If you are using java.util.Date you can use the method getDay(). It returns Calendar constant, like Calendar.MONDAY.
You can pass the string as 02,2016
List<String> getWeekendsOftheMonth(String monthYearString) {
long monthDate;
List<String> weekEnds = new ArrayList<>();
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd,MM,yyyy");
try {
monthYearString="01,".concat(monthYearString);
monthDate = simpleDateFormat.parse(monthYearString).getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(monthDate);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
int minDate = calendar.getActualMinimum(Calendar.DATE);
for (int i = minDate; i <= maxDate; i++) {
calendar.set(Calendar.DATE, i);
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
weekEnds.add(convertToDate(calendar.getTimeInMillis()));
}
}
}catch (Exception e){
e.printStackTrace();
}
return weekEnds;
}
String convertToDate(Long datetime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM. yyyy");
Date date = new Date(datetime);
return simpleDateFormat.format(date);
}
you can do it from this method.

Android difference between two dates?

I getting two date from calendars.It writing into a string builder.I want to getting difference between two date also I want to keep the number of days remaining between times,except weekends.
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
if (cur == DATE_DIALOG_ID) {
// set selected date into textview
permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString();
tvDisplayDate.setText("Date : " + permitDate);
} else {
startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString();
tvDisplayDate2.setText("Date : " + startDate);
}
}
};
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Use JodaTime library to find the difference between dates.
For more information follow the instructions Use Joda Time.

Get interval date in Android?

I want interval date. Whatever user enter date from date picker and from this date I want to get after one month date Suppose 1 Aug 2014 -> Output will be 1 September 2014.Can someone help me .Thanks to appreciate.
Hare is my Activity code
{
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Month is 0 based, just add 1
etReplacementDate.setText(new StringBuilder()
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
etReplacementDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_OF_REPLACEMENT);
}
});
String fixedDate = etReplacementDate.getText().toString().trim();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(fixedDate);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Date Consersion = " + convertedDate);
/****************ReplaceMent Date***************************************************/
cal2.add(Calendar.getInstance(convertedDate), 30);
Date date_30dayslater = cal2.getTime();
System.out.println("date_30dayslater : " + date_30dayslater);
/****************Interval Date***************************************************/
String _30daysLater_String = new SimpleDateFormat("yyyy-MM-dd").format(date_30dayslater);
etNextReplanishmentDate.setText(_30daysLater_String);
System.out.println("30 days later: " + _30daysLater_String);
System.out.println("______________________________________");
/****************Before Date***************************************************/
cal2.add(Calendar.DATE, -1);
Date beforDate = cal2.getTime();
String beforDate_String = new SimpleDateFormat("yyyy-MM-dd").format(beforDate);
System.out.println("beforDate_String: " + beforDate_String);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_OF_REPLACEMENT:return new DatePickerDialog(this, pickerListenerReplacement, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListenerReplacement = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
etReplacementDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
What you want to do is add() one Calendar.MONTH to a date that you've gotten and parsed, etc. so I won't go into that. I'll assume you are handling everything correctly up to the point where you'd like to get the same day, if possible, of the next month.
Part of your problem, as your comment suggests, is Calendar.getInstance() does not have an implementation that takes a Date. But more importantly you don't need it. You have a Date and a Calendar instance and it seems like you're changing c2 anyway so why not use Calendar's setTime() method like this?
// setting c2 with the convertedDate then adding a month
c2.setTime(convertedDate);
c2.add(Calendar.MONTH, 1);
// Simple example
public static void main(String...args) {
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println(c.getTime());
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
try to use this.
Calendar c = Calendar.getInstance();
int month = c.get((Calendar.MONTH));
c.set(Calendar.MONTH, month + 1);
long time = c.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String result = sdf.format(new Date(time1));

Android week View how can we Get all days of a next and previous week

I'm able to get current week dates, But How to list previous / next week days ?
This is the method
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
// System.out.println(Arrays.toString(days));
return days;
}
pls see the image, and tell me how to get the next and previous week days
finally i got the answer pls see this
Get the present Week:
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the Next Week:
int weekDaysCount=0;
public String [] getWeekDayNext()
{
weekDaysCount++;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the previous Week:
public String [] getWeekDayPrev()
{
weekDaysCount--;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
to assign the textView
NextPreWeekday = getWeekDay();
firstDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [0]);
lastDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [6]);
textViewDate.setText(firstDayOfWeek + "-" + lastDayOfWeek + " " + CommonMethod.convertWeekDaysMouth(NextPreWeekday [6]));
textViewSun.setText(CommonMethod.convertWeekDays(NextPreWeekday [0]) + "\nSun");
textViewMon.setText(CommonMethod.convertWeekDays(NextPreWeekday [1]) + "\nMon");
textViewTue.setText(CommonMethod.convertWeekDays(NextPreWeekday [2]) + "\nTue");
textViewWed.setText(CommonMethod.convertWeekDays(NextPreWeekday [3]) + "\nWeb");
textViewThu.setText(CommonMethod.convertWeekDays(NextPreWeekday [4]) + "\nThu");
textViewFri.setText(CommonMethod.convertWeekDays(NextPreWeekday [5]) + "\nFri");
textViewSat.setText(CommonMethod.convertWeekDays(NextPreWeekday [6]) + "\nSat");
public static String convertWeekDays(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("dd");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
public static String convertWeekDaysMouth(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("MMM yyyy");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
For current week.
SimpleDateFormat displayDate = new SimpleDateFormat("dd-MMM-yyyyy"));
final Calendar calenderThisWeek = Calendar.getInstance();
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
For Previous Week
final Calendar calenderpreviousWeek = Calendar.getInstance();
calenderpreviousWeek.add(Calendar.DAY_OF_WEEK, -1);
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderpreviousWeek.getTime()); // dd-mmm-yyyy
For Next Week
final Calendar calenderNextWeek = Calendar.getInstance();
calenderNextWeek.add(Calendar.DAY_OF_WEEK, +1);
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy

Categories

Resources