Set date in DatePickerDialog from String - java

How can I set date in a DatePicker from a string (eg: 02/10/19):
Following is the code:
iqp_editDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(ActivityClass.this, (DatePickerDialog.OnDateSetListener) date1, y, m, d).show();
}
});
DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
y = year;
m = month;
d = dayOfMonth;
dateMonth = month + 1;
dateYear = year;
}
};

Update: misunderstood the question:
Calendar cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY,18);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.DATE,2);
cal.set(Calendar.MONTH,9); //Month -1
//Or to set it from a String:
String string = "02/10/19";
DateFormat format = new SimpleDateFormat("dd/MM/yy", Locale.getDefault());
Date date = format.parse(string);
cal.setTimeInMillis(date.getTime());
new DatePickerDialog(getContext(),date1, cal
.get(Calendar.YEAR), cal .get(Calendar.MONTH),
cal .get(Calendar.DAY_OF_MONTH)).show();

A string is a character array. Meaning that you could just make a loop and set the different day, month and year values to different parts of the string.
String date = "02/19/19";
String year = "";
for(int i = 0; i < date.length; i++)
{
month += date.charAt(i);
...
}
Then you'd tell it when to switch from adding to month to day to year when it encounters '/'
if(date.charAt(i) == '/')
{
...
}
at the end of it all if you need to make it into an int then do
int month = Integer.parseInt("month");
sorry I've gotta be going somewhere so I couldn't just write the code out for ya but I'm sure you can figure it out from what I gave ya.

Following code works fine for me:
new DatePickerDialog(Activityclass.this, date1, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
view.setMinDate(1559327400);
y = year;
m = month;
d = dayOfMonth;
dateMonth = month + 1;
dateYear = year;
iqp_editDate.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
try {
epoch = new java.text.SimpleDateFormat("MM/dd/yyyy").parse(m + "/" + dayOfMonth + "/" + year).getTime() / 1000;
} catch (ParseException e) {
e.printStackTrace();
}
}
};

Related

Cannot get data from SQLite Room Database using dates

I have a typeconverter that goes like this
public class DateConverter {
#TypeConverter
public static Date convertLongToDate(Long dateLong) {
return dateLong == null ? null : new Date(dateLong);
}
#TypeConverter
public static Long convertDateToLong(Date date) {
return date == null ? null : date.getTime();
}
...
}
And I use it in my database
#Database(entities = { LoginEntity.class,
Transaction.class,
UnsentTagNumbers.class }, version = 11, exportSchema = false)
#TypeConverters(DateConverter.class)
public abstract class ApplicationDatabase extends RoomDatabase {
public abstract LoginDao loginDao();
...
}
In inserting the transaction to the database, I do it like so.
public void recordTransaction() {
transaction.setTransactionDate(Calendar.getInstance().getTime()); <==== Please take note on the way that I use the current date.
transaction.setTransactionType(getApplication().getString(R.string.exit_scan));
...
transactionRepository.insert(transaction);
}
In my DAO
#Query("SELECT * FROM TRANSACTION_TABLE WHERE transactionDate >= :fromDate AND transactionDate <= :toDate AND staffId = :staffId")
LiveData<List<Transaction>> getTransactionSummaryByDates(Date fromDate, Date toDate, String staffId);
This is how I search for the transactions by dates
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartDate:
if(!hasSelectedStaffId) {
Toast.makeText(this, "Select a staff id first.", Toast.LENGTH_SHORT).show();
return;
}
Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
dpdStartDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
hasSelectedStartDate = true;
startDate = new Date(year, monthOfYear, dayOfMonth, 0, 0, 0);
btnStartDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
dpdStartDate.show();
break;
case R.id.btnEndDate:
cldr = Calendar.getInstance();
day = cldr.get(Calendar.DAY_OF_MONTH);
month = cldr.get(Calendar.MONTH);
year = cldr.get(Calendar.YEAR);
dpdEndDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
endDate = new Date(year, monthOfYear, dayOfMonth, 23, 59, 59);
btnEndDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
if (hasSelectedStartDate && hasSelectedStaffId) {
viewModel.getTransactions(startDate, endDate, selectedStaffId);
transactionAdapter.setTransactionList(transactionList);
transactionAdapter.notifyDataSetChanged();
}
}
}, year, month, day);
dpdEndDate.show();
break;
}
}
And this is in my viewmodel to get the transactions
public void getTransactions(Date startDate, Date endDate, String staffId) {
transactionList = transactionRepository.getTransactionSummaryByDates(startDate, endDate, staffId);
}
How come, I do not get any information from the database? If I check my database, the transactions are recorded. Please see image.
This is the parameters I send so I can get via dates
startDate: Wed Jan 25 00:00:00 GMT+08:00 3922
endDate: Thu Jan 26 23:59:59 GMT+08:00 3922
staffId: 10164
But if I convert my dates that I get from the datepicker to epoch like this:
if (hasSelectedStartDate && hasSelectedStaffId) {
Long lStartDate = startDate.getTime();
Long lEndDate = endDate.getTime();
viewModel.getTransactions(lStartDate, lEndDate, selectedStaffId);
//viewModel.getTransactions(startDate, endDate, selectedStaffId);
//setupTransactionList();
}
I've noticed that in my database, the date is 16431... But when I query and I convert my date parameters, it is 6060....
How do I make this right?
The mistake I had was in the codes of my onClick(View ...). I just converted my Date Pickers to Calendar and got the time from it like so..
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartDate:
if(!hasSelectedStaffId) {
Toast.makeText(this, "Select a staff id first.", Toast.LENGTH_SHORT).show();
return;
}
Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
dpdStartDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
hasSelectedStartDate = true;
cldr.set(year, monthOfYear, dayOfMonth, 23, 59, 59);
startDate = cldr.getTime(); //new Date(year, monthOfYear, dayOfMonth, 0, 0, 0);
btnStartDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
dpdStartDate.show();
break;
case R.id.btnEndDate:
if(!hasSelectedStaffId) {
Toast.makeText(this, "Select a staff id first.", Toast.LENGTH_LONG).show();
return;
}
if(!hasSelectedStartDate) {
Toast.makeText(this, "Select a start date first.", Toast.LENGTH_LONG).show();
return;
}
cldr = Calendar.getInstance();
day = cldr.get(Calendar.DAY_OF_MONTH);
month = cldr.get(Calendar.MONTH);
year = cldr.get(Calendar.YEAR);
dpdEndDate = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
cldr.set(year, monthOfYear, dayOfMonth, 23, 59, 59);
endDate = cldr.getTime();
btnEndDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
if (hasSelectedStartDate && hasSelectedStaffId) {
viewModel.getTransactions(startDate, endDate, selectedStaffId);
setupTransactionList();
}
}
}, year, month, day);
dpdEndDate.show();
break;
}
}
The endDate = new Date(year, monthOfYear, dayOfMonth, 23, 59, 59); had a different format so since I was using the "Calendar" instance when saving, I figured that it should have been a "Calendar" instance that I should be passing as parameters.

To disable every sunday in calendar view in android

How to disable only sunday in the following code?
We cannot find any solution to disable sunday for a month
MainActivity.java:
CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
Calendar calendar = Calendar.getInstance();
calendarView.setMinDate(calendar.getTimeInMillis());
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener()
{
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Toast.makeText(getApplicationContext(), "" + dayOfMonth, 0).show();// TODO Auto-generated method stub`enter code here`
}
});
I have used this code in a project. See if it produces desirable result -
//Global Variables
private Calendar lastSelectedCalendar = null;
private CalendarView calendarView;
//
calendarView = (CalendarView) findViewById(R.id.calendarView);
lastSelectedCalendar = Calendar.getInstance();
calendarView.setMinDate(lastSelectedCalendar.getTimeInMillis() - 1000);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Calendar checkCalendar = Calendar.getInstance();
checkCalendar.set(year, month, dayOfMonth);
if(checkCalendar.equals(lastSelectedCalendar))
return;
if(checkCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
calendarView.setDate(lastSelectedCalendar.getTimeInMillis());
else
lastSelectedCalendar = checkCalendar;
}
});
Calendar sunday;
List<Calendar> weekends = new ArrayList<>();
int weeks = 5;
for (int i = 0; i < (weeks * 7) ; i = i + 7) {
sunday = Calendar.getInstance();
sunday.add(Calendar.DAY_OF_YEAR, (Calendar.SUNDAY - sunday.get(Calendar.DAY_OF_WEEK) + 7 + i));
// saturday = Calendar.getInstance();
// saturday.add(Calendar.DAY_OF_YEAR, (Calendar.SATURDAY - saturday.get(Calendar.DAY_OF_WEEK) + i));
// weekends.add(saturday);
weekends.add(sunday);
}
Calendar[] disabledDays = weekends.toArray(new Calendar[weekends.size()]);
dpd.setDisabledDays(disabledDays);
This code disables the next 5 Sundays, if you wish to do it for a longer period, just need to modify week. If you wish to disable Saturdays too, just uncomment those lines.
If you want to do it for previous 5 Sundays then, just modify the for loop to:
for (int i = 0; i < (weeks * 7); i = i + 7) {
for(int j =0; j > (weeks*7) ; j = j - 7);
sunday = Calendar.getInstance();
sunday.add(Calendar.DAY_OF_YEAR, (Calendar.SUNDAY - sunday.get(Calendar.DAY_OF_WEEK) + 7 + i));
// saturday = Calendar.getInstance();
// saturday.add(Calendar.DAY_OF_YEAR, (Calendar.SATURDAY - saturday.get(Calendar.DAY_OF_WEEK) + i));
// weekends.add(saturday);
weekends.add(sunday);
}

Java check todays date is biweekly tuesday

I have a couple of requirement, I need to validate if today's date is matching with a condition and if true create records in DB.
but the condition is something like this - biweekly Tuesday, biweekly Thursday.
Can anybody provide how to achieve this?
private static Calendar cacheCalendar;
public static LocalDate getNDayOfMonth(int dayweek, int nthweek, int month, int year) {
LocalDate d = new LocalDate(year, month, 1).withDayOfWeek(dayweek);
if (d.getMonthOfYear() != month)
d = d.plusWeeks(1);
return d.plusWeeks(nthweek - 1);
}
public static LocalDate getLastWeekdayOfMonth(int dayweek, int month, int year) {
LocalDate d = new LocalDate(year, month, 1).plusMonths(1).withDayOfWeek(dayweek);
if (d.getMonthOfYear() != month)
d = d.minusWeeks(1);
return d;
}
public static void main(String[] args) {
cacheCalendar = Calendar.getInstance();
for (int i = 1; i < 13; i++) {
// second wednesday of oct-2011
LocalDate secondMonday = getNDayOfMonth(DateTimeConstants.MONDAY, 2, i, cacheCalendar.get(Calendar.YEAR));
System.out.println("secondMonday= " + secondMonday);
LocalDate secondTuesday = getNDayOfMonth(DateTimeConstants.TUESDAY, 2, i,
cacheCalendar.get(Calendar.YEAR));
System.out.println("secondTuesday= " + secondTuesday);
LocalDate monthlyTuesday = getNDayOfMonth(DateTimeConstants.TUESDAY, 1, i,
cacheCalendar.get(Calendar.YEAR));
System.out.println("monthlyTuesday= " + monthlyTuesday);
LocalDate weeklyFirstFriday = getNDayOfMonth(DateTimeConstants.FRIDAY, 1, i,
cacheCalendar.get(Calendar.YEAR));
System.out.println("weeklyFirstFriday= " + weeklyFirstFriday);
}
}

Setting upper and lower date limits to date picker dialog

I have created an activity in which there is a field for inserting birth date of the user. I have used a date picker to achieve this.
This is the source code of what I am doing:
// onclick dob edittext open date picker dialog
dob.setFocusableInTouchMode(false);
dob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//open date picker
showDialog(DATE_DIALOG_ID);
}
});
//======================For picking birth day==========================
// Creating dialog
#Override
protected Dialog onCreateDialog(int id) {
Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
// onDateSet method
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// String date_selected = String.valueOf(monthOfYear+1)+" /"
// +String.valueOf(dayOfMonth)+" /"
// +String.valueOf(year);
String date_selected = String.valueOf(dayOfMonth)+" /"
+String.valueOf(monthOfYear+1)+" /"
+String.valueOf(year);
//Toast.makeText(RegisterActivity.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
dob.setText(date_selected);
}
};
//======================For picking birth day==========================
Now what I want to do is, to limit the date picker to particular year.
Like this:
int maxYear = c.get(Calendar.YEAR) - 15; // this year ( 2013 ) - 15 = 1998
int maxMonth = c.get(Calendar.MONTH);
int maxDay = c.get(Calendar.DAY_OF_MONTH);
int minYear = maxYear-49;
int minMonth = 0; // january
int minDay = 25;
What should I do to set the above mentioned bounding to the date picker?
//----------------Edit---------------------------
I have done something like this:
//======================For picking birth day==========================
// Creating dialog
#Override
protected Dialog onCreateDialog(int id) {
Calendar c = Calendar.getInstance();
maxYear = c.get(Calendar.YEAR) - 15; // this year ( 2013 ) - 15 = 1998
maxMonth = c.get(Calendar.MONTH);
maxDay = c.get(Calendar.DAY_OF_MONTH);
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, maxYear, maxMonth, maxDay);
}
return null;
}
DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
int minYear = maxYear-49;
int minMonth = 0; // january
int minDay = 25;
public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
Date current = new Date(year, monthOfYear, dayOfMonth);
Date minDate = new Date(minYear, minMonth, minDay);
Date maxDate = new Date(maxYear, maxMonth, maxDay);
if( current.getTime() < minDate.getTime() )
{
//set to minimum date
}else if( current.getTime() > maxDate.getTime() )
{
//Set to max Date
}
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
String date_selected = String.valueOf(dayOfMonth)+" /"
+String.valueOf(monthOfYear+1)+" /"
+String.valueOf(year);
//Toast.makeText(RegisterActivity.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
dob.setText(date_selected);
}
};
//======================For picking birth day==========================
This is fixing the upper limit, but the lower limit or the minDate is not getting fixed! What is to be done?
Set OnDateChangedListener() For you DatePicker and inside onDateChanged function if the date set is greater than the decide limit if so DatePicker.updateDate(minYear, minMonth, minDay); use this method to reset it.
Date minDate = new Date(1990, 10, 25);
Date maxDate = new Date(2013, 4, 15);
OnDateChangedListener listener = new OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Date current = new Date(year, monthOfYear, dayOfMonth);
if( current.getTime() < minDate.getTime() )
{
//set to minimum date
}else if( current.getTime() > maxDate.getTime() )
{
//Set to max Date
}
}
};
YourDatePicker.init(2013, 4, 15, listener);

Java calendar getting weekdays not working

I am trying to get this to output all the weekdays (MON-FRI) between 5/16/2010 (a sunday) and 5/25/2010 (a tuesday). The correct output should be 17,18,19,20,21,24,25. However, the result im getting is 17,18,19,20,21,17,18,19. The other methods just split up the string the date is in
import java.util.*;
public class test
{
public static void main(String[] args) {
String startTime = "5/16/2010 11:44 AM";
String endTime = "5/25/2010 12:00 PM";
GregorianCalendar startCal = new GregorianCalendar();
startCal.setLenient(true);
String[] start = splitString(startTime);
//this sets year, month day
startCal.set(Integer.parseInt(start[2]),Integer.parseInt(start[0])-1,Integer.parseInt(start[1]));
startCal.set(GregorianCalendar.HOUR, Integer.parseInt(start[3]));
startCal.set(GregorianCalendar.MINUTE, Integer.parseInt(start[4]));
if (start[5].equalsIgnoreCase("AM")) { startCal.set(GregorianCalendar.AM_PM, 0); }
else { startCal.set(GregorianCalendar.AM_PM, 1); }
GregorianCalendar endCal = new GregorianCalendar();
endCal.setLenient(true);
String[] end = splitString(endTime);
endCal.set(Integer.parseInt(end[2]),Integer.parseInt(end[0])-1,Integer.parseInt(end[1]));
endCal.set(GregorianCalendar.HOUR, Integer.parseInt(end[3]));
endCal.set(GregorianCalendar.MINUTE, Integer.parseInt(end[4]));
if (end[5].equalsIgnoreCase("AM")) { endCal.set(GregorianCalendar.AM_PM, 0); }
else { endCal.set(GregorianCalendar.AM_PM, 1); }
for (int i = startCal.get(Calendar.DATE); i < endCal.get(Calendar.DATE); i++)
{
startCal.set(Calendar.DATE, i);
startCal.set(Calendar.DAY_OF_WEEK, i);
if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
{
System.out.println("\t" + startCal.get(Calendar.DATE));
}
}
}
private static String[] splitDate(String date)
{
String[] temp1 = date.split(" "); // split by space
String[] temp2 = temp1[0].split("/"); // split by /
//5/21/2010 10:00 AM
return temp2; // return 5 21 2010 in one array
}
private static String[] splitTime(String date)
{
String[] temp1 = date.split(" "); // split by space
String[] temp2 = temp1[1].split(":"); // split by :
//5/21/2010 10:00 AM
String[] temp3 = {temp2[0], temp2[1], temp1[2]};
return temp3; // return 10 00 AM in one array
}
private static String[] splitString(String date)
{
String[] temp1 = splitDate(date);
String[] temp2 = splitTime(date);
String[] temp3 = new String[6];
return dateFill(temp3, temp2[0], temp2[1], temp2[2], temp1[0], temp1[1], temp1[2]);
}
private static String[] dateFill(String[] date, String hours, String minutes, String ampm, String month, String day, String year) {
date[0] = month;
date[1] = day;
date[2] = year;
date[3] = hours;
date[4] = minutes;
date[5] = ampm;
return date;
}
private String dateString(String[] date) {
//return month+" "+day+", "+year+" "+hours+":"+minutes+" "+ampm
//5/21/2010 10:00 AM
return date[3]+"/"+date[4]+"/ "+date[5]+" "+date[0]+":"+date[1]+" "+date[2];
}
}
startCal.set(Calendar.DAY_OF_WEEK, i); Will flip flip your date back every 7 loops.
This code isn't good.
I don't understand why you're doing all this parsing of Strings to get to Date and visa versa when you have java.text.DateFormat and java.text.SimpleDateFormat to do it easily for you.
I think this is better. See if you agree:
package com.contacts.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtils
{
private static final DateFormat DEFAULT_FORMAT = new SimpleDateFormat("dd-MMM-yyyy");
public static void main(String[] args)
{
try
{
Date startDate = ((args.length > 0) ? DEFAULT_FORMAT.parse(args[0]) : new Date());
Date endDate = ((args.length > 1) ? DEFAULT_FORMAT.parse(args[1]) : new Date());
List<Date> weekdays = DateUtils.getWeekdays(startDate, endDate);
Calendar calendar = Calendar.getInstance();
for (Date d : weekdays)
{
calendar.setTime(d);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
// System.out.println(DEFAULT_FORMAT.format(d));
System.out.println("day: " + dayOfMonth + " month: " + (month+1) + " year: " + year);
}
}
catch (ParseException e)
{
e.printStackTrace();
}
}
public static List<Date> getWeekdays(Date startDate, Date endDate)
{
List<Date> weekdays = new ArrayList<Date>();
if ((startDate == null) || (endDate == null))
return weekdays;
if (startDate.equals(endDate))
{
if (isWeekday(startDate))
{
weekdays.add(startDate);
}
}
else if (startDate.after(endDate))
{
weekdays = getWeekdays(endDate, startDate);
}
else
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
Date d = startDate;
while (endDate.equals(d) || endDate.after(d))
{
if (isWeekday(d))
{
weekdays.add(d);
}
calendar.add(Calendar.DATE, 1);
d = calendar.getTime();
}
}
return weekdays;
}
public static boolean isWeekday(Date d)
{
if (d == null)
return false;
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
return ((dayOfWeek >= Calendar.MONDAY) && (dayOfWeek <= Calendar.FRIDAY));
}
}
I don't know if this is an issue with your code, but JDK uses some unexpected values for Calendar constants. For example, months star with zero. In other words, Calendar.JANUARY is 0. On the other hand, weekdays are 1 to 7, starting with Sunday as 1. etc.
I luckily don't know much about Date in Java, but I know it's basically a difficult and bad API. Go for JodaTime until the new JSR-310 is done.

Categories