Get available days between two days in java - java

I am newly for java, and i want to build booking system and now i try to get available days between two days without booked days. but, however my code running bad.
this is my code
Connection connection = DBConnection.getInstance().getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from A");
ResultSet executeQuery = preparedStatement.executeQuery();
while (executeQuery.next()) {
String refid = executeQuery.getString("REFID");
statDate = executeQuery.getDate("Start_date");
endDate = executeQuery.getDate("End_date");
System.out.println("ref no : " + refid + " statDate :" + statDate + " end date :" + endDate);
System.out.println("\n");
int month = statDate.getMonth();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//
for (int i = 1; i < maxDay; i++) {
cal.set(Calendar.DAY_OF_MONTH, i + 1);
String format = df.format(cal.getTime());
dateOfMonth.add(format);
addDays = addDays(statDate, 2);
if (df.format(cal.getTime()).equals("" + statDate) || df.format(cal.getTime()).equals("" + endDate)) {
//System.out.println(statDate + " is not available !");
System.out.println("---");
} else {
int bDays = endDate.getDate() - statDate.getDate();
//System.out.println(bDays);
//===========
List<DateTime> between = getDateRange(DateTime.parse(statDate.toString()), DateTime.parse(endDate.toString()));
for (DateTime dateTime : between) {
Date da = dateTime.toDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
dateOfBooked.add(sdf.format(da));
}
System.out.println(df.format(cal.getTime()));
}
}
System.out.println("\n");
}
this is my db script
insert into A values('1','ref1','2018-02-18','2018-02-25');
insert into A values('2','ref1','2018-03-10','2018-03-17');
insert into A values('3','ref1','2018-03-20','2018-03-27');
i try to get available days from thees booked days. how can i print only available days ?
output

Related

how to convert multiple format of dates into only one format using java

from the database postgressql i'm getting date sometime date in different different forlamts like "2015-11-26 09:30:10","2015-11-26 09:30:10.080","2015-11-26 09:30:10.000" now i want to convert all format as only this format 22/01/2018 how to do in java.
try {
Date theDate1 = new Date("JAN 13,2014 09:15");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e {
System.out.println(e.toString());
}
i got output as Hello, World !13 / 01 / 2014 but when i tried
try {
Date theDate1 = new Date("2017-11-27 00:00:00");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
System.out.println(e.toString());
}
then i got java.lang.IllegalArgumentExceptionhow to solve this problem
Try this
String text = "JAN 13,2014 09:15";
String patternst = "\\d\\d\\d\\d-\\d\\d-\\d\\d*";
Pattern pattern = Pattern.compile(patternst);
Matcher matcher = pattern.matcher(text);
String data = "";
while (matcher.find()) {
data = matcher.group(0);
}
try {
int year = Integer.parseInt(data.split("-")[0]);
int month = Integer.parseInt(data.split("-")[1]);
int day = Integer.parseInt(data.split("-")[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
Date theDate1 = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
Date theDate1 = new Date(text);
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
}

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.

How to get the list of dates in a given date range?

I am trying to get the list of dates between in a date range in iso format ("yyyy-MM-dd"), as follows:
ArrayList<String> datesList = new ArrayList<String>();
try {
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd");
int[] fromDateParts = new int[3];
for (int f = 0; f < fromIsoDate.split("-").length; f++) {
fromDateParts[f] = Integer.parseInt(fromIsoDate.split("-")[f]);
System.out.println("fromDateParts[" + f + "] : " + fromDateParts[f]);
}
int[] toDateParts = new int[3];
for (int t = 0; t < toIsoDate.split("-").length; t++) {
toDateParts[t] = Integer.parseInt(toIsoDate.split("-")[t]);
System.out.println("toDateParts[" + t + "] : " + toDateParts[t]);
}
Calendar fromDate = new GregorianCalendar(fromDateParts[0], fromDateParts[1], fromDateParts[2]);
Calendar toDate = new GregorianCalendar(toDateParts[0], toDateParts[1], toDateParts[2]);
System.out.println("fromDate " + fromDate + " toDate " + toDate);
boolean hasMoreDays = true;
while (hasMoreDays) {
if ((fromDate.before(toDate)) || (fromDate.equals(toDate))) {
datesList.add(isoFormat.format(fromDate));
fromDate.add(Calendar.DAY_OF_MONTH, 1);
} else {
hasMoreDays = false;
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception : While determining the dates in between " + fromIsoDate + " and " + toIsoDate + "!");
}
But, it throws error:
java.lang.IllegalArgumentException: Cannot format given Object as a Date.
Please guide me in getting the list of dates between in a date range!
Just wrap your start date in a Calendar and use that:
Date startDate;
Date endDate;
Calendar c = Calendar.getInstance();
c.setTime(startDate);
Date dt = startDate;
List<Date> dates = new ArrayList<>();
do {
dates.add(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
} while (endDate.getTime() > dt.getTime());
As you would expect to hear, the Java 8 API or possibly JodaTime might make your life easier than using the Java 7 date way of things.
You should pass a Date to your SimpleDateFormat.fotmat inntead of Calendar:
datesList.add(isoFormat.format(fromDate));
to
datesList.add(isoFormat.format(fromDate.getTime));
And below is my solution for your request:
String fromStr = "2016-11-01";
String toStr = "2016-11-17";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar from = Calendar.getInstance();
from.setTime(sdf.parse(fromStr));
Calendar to = Calendar.getInstance();
to.setTime(sdf.parse(toStr));
List<Date> retval = new ArrayList<Date>();
while (from.before(to) || from.equals(to)) {
retval.add(from.getTime());
System.out.println(sdf.format(from.getTime()));
from.add(Calendar.DATE, 1);
}
Hope this help!
If you use java8 you can write the whole stuff in one line as shown below, I have used java.util.Date
List<Date> dates = new ArrayList<>();
Date fromDate = new Date(2016, 11, 02);
Date toDate = new Date(2016, 11, 28);
dates.add(new Date(2016, 11, 01));
dates.add(new Date(2016, 11, 02));
dates.add(new Date(2016, 11, 03));
dates.add(new Date(2016, 11, 04));
List<Date> filteredDates = dates.stream()
.filter((e) -> e.after(fromDate) && e.before(toDate)).collect(Collectors.toList());

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

Java: Date Time Conversion

I have a date format like "SA25MAY"; I need to convert it into date time variable and then I want to add one day in that. And then I need to return the answer in same format. Please do some needful
try {
String str_date = "SA25MAY";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("ddd-dd-MMM");
date = (Date) formatter.parse(str_date);
System.out.println("Today is " + date);
} catch (Exception e) {
e.printStackTrace();
}
ERROR:
java.text.ParseException: Unparseable date: "SA25MAY"
at java.text.DateFormat.parse(DateFormat.java:337)
at javadatatable.JavaDataTable.main(JavaDataTable.java:29)
Here I don't know how to resolve this problem.
ddd can not match SUN. Use EEE instead if you want to match the day name in the week.
You can only add one day if you know the year because of leap years (29th of February).
In case the year is the current year, the following solution should do the the job:
For "SA25MAY":
try {
String str_date = "SA25MAY";
// remove SA
str_date = str_date.replaceFirst("..", "");
// add current year
Calendar c = Calendar.getInstance();
str_date = c.get(Calendar.YEAR) + str_date;
// parse date
Date date;
SimpleDateFormat formatter = new SimpleDateFormat("yyyyddMMM");
date = formatter.parse(str_date);
System.out.println("Today is " + date);
// add day
c.setTime(date);
c.add(Calendar.DATE, 1);
// rebuild the old pattern with the new date
SimpleDateFormat formatter2 = new SimpleDateFormat("EEEddMMM");
String tomorrow = formatter2.format(c.getTime());
tomorrow = tomorrow.toUpperCase();
tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3);
System.out.println("Tomorrow is " + tomorrow);
} catch (Exception e) {
e.printStackTrace();
}
Or for "SA-25-MAY":
try {
String str_date = "SA-25-MAY";
// remove SA
str_date = str_date.replaceFirst("..-", "");
// add current year
Calendar c = Calendar.getInstance();
str_date = c.get(Calendar.YEAR) + "-" + str_date;
// parse date
Date date;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MMM");
date = formatter.parse(str_date);
System.out.println("Today is " + date);
// add day
c.setTime(date);
c.add(Calendar.DATE, 1);
// rebuild the old pattern with the new date
SimpleDateFormat formatter2 = new SimpleDateFormat("EEE-dd-MMM");
String tomorrow = formatter2.format(c.getTime());
tomorrow = tomorrow.toUpperCase();
tomorrow = tomorrow.substring(0, 2) + tomorrow.substring(3);
System.out.println("Tomorrow is " + tomorrow);
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources