I want to automate a date picker. The flow is:-
I want to detect the current date.
I want to select the date next to the current date.
The next date should be enabled not disabled (like sat, sun or holidays).
If it is disabled, then the logic should move to the next date and that date should be selected.
I am attaching the data picker type I'm working on.
Date picker
and the work I have done so far to select the next date. Current the program can go up to 3 dates only.
public void selectDate() {
String s;
String s1;
String s2;
String s3;
Date date;
Format formatter;
Calendar calendar = Calendar.getInstance();
date = calendar.getTime();
formatter = new SimpleDateFormat("d");
s = formatter.format(date);
System.out.println("Today : " + s);
calendar.add(Calendar.DATE, 1);
date = calendar.getTime();
formatter = new SimpleDateFormat("d");
s1 = formatter.format(date);
System.out.println("Tomorrow : " + s1);
calendar.add(Calendar.DATE, 1);
date = calendar.getTime();
formatter = new SimpleDateFormat("d");
s2 = formatter.format(date);
System.out.println("DayAfterTomorrow : " + s2);
calendar.add(Calendar.DATE, 1);
date = calendar.getTime();
formatter = new SimpleDateFormat("d");
s3 = formatter.format(date);
System.out.println("ThirdDayAfterToday : " + s3);
//find the calendar
List<WebElement> columns = date_Picker.findElements(By.xpath("//div[#class='bs-datepicker-body']/table/tbody/tr/td"));
//comparing the text of cell with today's date and clicking it.
for (WebElement cell : columns) {
if (cell.getText().equals(s1)) {
cell.click();
break;
}
if (cell.getText().equals(s2)) {
cell.click();
break;
}
if (cell.getText().equals(s3)) {
cell.click();
break;
}
}
}
Related
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());
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 6 years ago.
I'm working on an android application and new to it.
I have to get date from user and then add 28 days and store it in database.
This is what I have done so far
private void saveDate() throws ParseException {
DatabaseHelper db = new DatabaseHelper(ActivityPeriodToday.this.getActivity());
String pDate = periodDate.getText().toString().trim();
String pTime = periodTime.getText().toString().trim();
String next_expected = getNextExpected(pDate);
boolean isInserted = db.insertPeriodTodayIntoPeriods(pDate, pTime, early_late, pDifference, pType, next_expected);
if (isInserted == true) {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Could not be saved", Toast.LENGTH_SHORT).show();
}
}
private String getNextExpected(String pDate) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(pDate));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 28);
return sdf.format(c.getTime());
}
But is code is not incrementing month.
Ex. If user selects 01/11/2016, then date is incremented and is saved
29/11/2016. But if user selects 16/11/2016 then saves date is
28/11/2016 but this should be 14/12/2016
Step 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dateInString));
Step-2 use add() to add number of days to calendar
c.add(Calendar.DATE, 40);
Try using this:
calendar.add(Calendar.DAY_OF_YEAR, 28);
Its Working for me.
Calendar c = Calendar.getInstance();
int Year = c.get(Calendar.YEAR);
int Month = c.get(Calendar.MONTH);
int Day = c.get(Calendar.DAY_OF_MONTH);
// current date
String CurrentDate = Year + "/" + Month + "/" + Day;
String dateInString = CurrentDate; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateInString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 28);//insert the number of days that you want
sdf = new SimpleDateFormat("dd/MM/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
Toast.makeText(MainActivity.this, ""+dateInString, Toast.LENGTH_SHORT).show();
Your question may already have an answer here: How can I increment a date by one day in Java?
Or you can simply use
c.add(Calendar.DATE, 28);
instead of
c.add(Calendar.DAY_OF_MONTH, 28);
I have a timestamp and I want to check whether the time is before or after a certain time (9:00 AM). To be more specific, I want to know whether a person is late or not and the cut-off time is 9 AM. How do I code this?
2015-09-22 08:59:59 //Print on time
2015-09-22 09:00:00 //Print on time
2015-09-22 09:00:01 //Print you are late
I think you can do like:
public static final String TIME_STAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) {
Date standard = getStandardDate();
SimpleDateFormat format = new SimpleDateFormat(TIME_STAMP_FORMAT);
List<String> data = new ArrayList<String>();
data.add("2015-09-22 08:59:59");
data.add("2015-09-22 09:00:00");
data.add("2015-09-22 09:00:01");
for (String date : data) {
if(isLate(date, format)) {
System.out.println(date + " is Late");
} else {
System.out.println(date + " is On Time");
}
}
}
/**
* check is Late or not
* */
public static boolean isLate(String date, SimpleDateFormat format) {
Date standard = getStandardDate();
Date inputDate = null;
boolean result = false;
try {
inputDate = format.parse(date);
if(inputDate.after(standard)) {
result = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* get standard date
* */
public static Date getStandardDate() {
Date dateNow = new Date ();
Calendar cal = Calendar.getInstance();
cal.setTime(dateNow);
cal.set(Calendar.DAY_OF_MONTH, 22);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
Hope this help!
You can have code similar to following
// Get the provided date and time
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar providedDate = Calendar.getInstance();
providedDate.setTime(df.parse(stringInstanceRepresentingDate));
// Get the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 09:00
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 09:00 today
boolean afterNine = providedDate.after(cal);
if (afterNine ) {
System.out.println("You are late");
}
else {
System.out.println("You are not late");
}
Assuming the input is a String, you can do the following
String input = ...;
String time = input.split(" ")[1],
hour = time.split(":")[0],
minute = time.split(":")[1],
seconds = time.split(":")[2];
if(Integer.parseInt(hour) > 9 && Integer.parseInt(minute) > 0) {
// Not on time
}
This is assuming the input is always perfect though, you should use try-catch blocks or check the input beforehand as this could throw exceptions.
LocalDateTime time = LocalDateTime.of(2015, 9, 22, 9, 0, 0);
LocalDateTime now = LocalDateTime.now();
if (now.compareTo(time) > 0)
System.out.println("You are late");
else System.out.println("You are in time");
If you are working with strings you have to split them first, as mentioned by #Deximus
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));
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();
}