Date calculator : Selenium Web Driver - java

How can I verify if the calculated date is correct through selenium web driver?
Consider the following examples below:
From Date: 01/01/2001
Duration: 10
To Date: 01/10/2001
I will instruct selenium to input a date on from date field and duration.
The system shall automatically calculates the To date based on the inputted from date and duration.
I wonder if there's a way to verify if the calculated To Date is correct given that the inputted values on from date and duration fields may change time to time.
Static values for from date and duration fields is okay too - I guess.
Thanks!

You can do this using java.util methods. I assume you will be pass From Date and Duration as string to your selenium/webdriver from your test data set. You have to do following for each test data:
Calculate the To Date using util method (Code below for getToDate).
Get text in To Date using selenium/webdriver, for your test data.
Compare the text fetched by selenium/webdriver with the text returned by your getToDate method.
The method to get To Date:
public static String getToDate(String fromDate, String duration){
try {
String[] arrFromDate = fromDate.split("/");
int fromMonth = Integer.parseInt(arrFromDate[0])-1;
int fromDay = Integer.parseInt(arrFromDate[1]);
int fromYear = Integer.parseInt(arrFromDate[2]);
int intDuration = Integer.parseInt(duration);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, fromDay);
cal.set(Calendar.MONTH, fromMonth);
cal.set(Calendar.YEAR, fromYear);
cal.add(Calendar.DAY_OF_MONTH, intDuration);
String toDate = sdf.format(cal.getTime());
return toDate;
} catch (NumberFormatException e) {
e.printStackTrace();
return null;
}
Code to verify:
String appToDate = driver.findElement(By.id("toDate")).getText();
String myToDate = getToDate("01/01/2001","10");
boolean isToDateCorrect = false;
if (appToDate.equals(myToDate )){
isToDateCorrect = true;
}

I suggest parsing the date instead of splitting the string
String strDate = "01/01/2001";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = simpleDateFormat.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 10); // 10 == duration
String outStr = simpleDateFormat.format(calendar.getTime());

Related

Gettting date in dd/mm/yyyy format using Horizontal-Calendar library (Mulham-Raee/Horizontal-Calendar) calendar

I am looking to get date in dd/mm/yyyy format using Horizontal-calendar (Mulham-Raee library). I get corrent day and year but I cannot figure out to get correct month. My code is :
//define your start and end dates to set the range of the calendar:
/* starts before 1 month from now */
Calendar startDate = Calendar.getInstance();
startDate.add(Calendar.MONTH, -1);
final HorizontalCalendar horizontalCalendar;
/* ends after 1 month from now */
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.MONTH, 1);
//Then setup HorizontalCalendar in your Activity through its Builder:
horizontalCalendar = new HorizontalCalendar.Builder(this, R.id.calendarView)
.range(startDate, endDate)
.datesNumberOnScreen(5)
.build();
horizontalCalendar.setCalendarListener(new HorizontalCalendarListener() {
#Override
public void onDateSelected(Calendar date, int position) {
//do something
Calendar cal = horizontalCalendar.getDateAt(position);
cal.add(Calendar.DATE,1);
SimpleDateFormat format1 = new SimpleDateFormat("dd/mm/yyyy");
String formatted = format1.format(cal.getTime());
Log.d("Selected Date", formatted);
}
});
You have used the small letter 'mm for parsing month. Please use capital 'MM'
new SimpleDateFormat("dd/MM/yyyy");
You can find more about parsing pattern here
use this format dd/MM/yyyy intead of dd/mm/yyyy.Let me know if it's works for you.

how to get years, months and days from date of birth in java [duplicate]

I have a Date object in Java stored as Java's Date type.
I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).
With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.
I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?
I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.
My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.
I'm still a newbie to Java and am getting a bit puzzled by this.
Use something like:
Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.
Beware, months start at 0, not 1.
Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.
With Java 8 and later, you can convert the Date object to a LocalDate object and then easily get the year, month and day.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Note that getMonthValue() returns an int value from 1 to 12.
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("MMMM");
System.out.println("MONTH "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("YYYY");
System.out.println("YEAR "+simpleDateFormat.format(date).toUpperCase());
EDIT: The output for date = Fri Jun 15 09:20:21 CEST 2018 is:
DAY FRIDAY
MONTH JUNE
YEAR 2018
You could do something like this, it will explain how the Date class works.
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
String yourDateString = "02/28/2012 15:00:00";
SimpleDateFormat yourDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date yourDate = yourDateFormat.parse(yourDateString);
if (yourDate.after(currentDate)) {
System.out.println("After");
} else if(yourDate.equals(currentDate)) {
System.out.println("Same");
} else {
System.out.println("Before");
}
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
It might be easier
Date date1 = new Date("31-May-2017");
OR
java.sql.Date date1 = new java.sql.Date((new Date()).getTime());
SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM");
SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY");
String currentDay = formatNowDay.format(date1);
String currentMonth = formatNowMonth.format(date1);
String currentYear = formatNowYear.format(date1);
Date queueDate = new SimpleDateFormat("yyyy-MM-dd").parse(inputDtStr);
Calendar queueDateCal = Calendar.getInstance();
queueDateCal.setTime(queueDate);
if(queueDateCal.get(Calendar.DAY_OF_YEAR)==Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
{
"same day of the year!";
}
#Test
public void testDate() throws ParseException {
long start = System.currentTimeMillis();
long round = 100000l;
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay(new Date());
}
long mid = System.currentTimeMillis();
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay2(new Date());
}
long end = System.currentTimeMillis();
System.out.println(mid - start);
System.out.println(end - mid);
}
public static Date getYearMonthDay(Date date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyyyMMdd");
String dateStr = f.format(date);
return f.parse(dateStr);
}
public static Date getYearMonthDay2(Date date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
return c.getTime();
}
public static int compare(Date today, Date future, Date past) {
Date today1 = StringUtil.getYearMonthDay2(today);
Date future1 = StringUtil.getYearMonthDay2(future);
Date past1 = StringUtil.getYearMonthDay2(past);
return today.compare // or today.after or today.before
}
getYearMonthDay2(the calendar solution) is ten times faster. Now you have yyyy MM dd 00 00 00, and then compare using date.compare

I want my string to converted to a day [duplicate]

This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 7 years ago.
I have this string
String s = "29/04/2015"
And I want it to produce the name of that day in my language, which is Norwegian.
For example:
29/04/2015 is "Onsdag"
30/04/2015 is "Torsdag"
How can I do this?
String dateString = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("E", Locale.no_NO);
String day = formatter.format(date);
Now day will have the day in given locale. Update
You need to configure an instance of DateFormat, with your locale, (take a look at https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html).
then parse the Date and get the day, as Dilip already suggests.
You can use date parsing combined with Locale settings to get the desired output. For e.g. refer following code.
String dateStr = "29/04/2015";
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date dt = dtf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
String m = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG_FORMAT, new Locale("no", "NO"));
System.out.println(m);
For more information about locale, visit Oracle Java Documentation.
First you will need to parse the String to a Date. Then use a Calendar to get the day of the week. You can use an array to convert it to the appropriate string.
// Array of Days
final String[] DAYS = {
"søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"
};
// Parse the date
final String source = "27/04/2015";
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = format.parse(source);
} catch (final ParseException e) {
e.printStackTrace();
}
// Convert to calendar
final Calendar c = Calendar.getInstance();
c.setTime(date);
final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
// Get the day's name
System.out.println("Day of Week: " + dayOfWeek);
System.out.println("Day = " + DAYS[dayOfWeek - 1]);
You need to parse your text with date to Date instance and then format it back to text. You can do it with SimpleDateFormat class which supports many patterns of dates like
dd/MM/yyyy for your original date,
and EEEE for full name of day in month.
While formatting you will also need to specify locale you want to use. To create Norway specific locale you can use for instance
Locale nor = Locale.forLanguageTag("no-NO");
So your code can look more or less like:
String text = "29/04/2015";
Locale nor = Locale.forLanguageTag("no-NO");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", nor);
SimpleDateFormat dayOfWeek = new SimpleDateFormat("EEEE", nor);
Date date = sdf.parse(text);
System.out.println(dayOfWeek.format(date));
Output: onsdag.
final int SUNDAY = 1;
final int ONSDAG = 2;
final int TORSDAG = 3;
....
....
String s = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day) {
case(ONSDAG):
dayString = "ONSDAG";
break;
....
}
EDIT: I just tested this and it actually starts from Sunday, and returns the value of 1 for sunday, I've changed the constant values to reflect this.
First you'll need a Calendar object.
Calendar cal = Calendar.getInstance();
String s = "29/04/2015"
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
cal.setTime(format.parse(s));
From the Calendar you can get the day of the week.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
dayOfWeek will be 1-7 with Sunday (in english) being 1
You can use an HashMap map where the first parametri is the date "29/4/2015" while the second is the meaning. You can use your string to get the meaning map.get (yourString).

How to remove millisec from date and time [duplicate]

This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 8 years ago.
I have a object that giving date and time in this format "2014-06-11 16:32:36.828".
I want to remove millisec .828.
In my db that object is in time stamp format but whenever i am showing i am converting it to tostring().
so how to remove millisec please help me
The following code convert "2014-06-11 16:32:36.828" into "2014-06-11 16:32:36"
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828"));
Explanation:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828") parse the input string into
Wed Jun 11 16:32:36 IST 2014
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) format the input date into specified structure.
I would use DateUtils.truncate(date, Calendar.SECOND)
Date d = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(yourString);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
I remember there is a way to directly read Date off your timestamp field but I don't do that in my everyday coding. So I'd left for others to post so. Nevertheless, you can use the same above code to translate your date from that timestamp into a date without MILLISECOND.
If you receive it as a Timestamp, you should use the appropriate formatter when converting it to a string:
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
Note: this will use the default time zone of the local computer.
Extract epoch millis from the original Date object and do integer division by 1000 followed by multiplication by 1000. Create Date object with the time zone of the original object and the millis calculated the above suggested way.
You can get the system time as follows without milliseconds
import java.text.SimpleDateFormat;
import java.util.Calendar;
And the code
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-YYYY-hh:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println(dateNow);
if you want to mantain the format try something like that:
public static String getFechaTimestampToString (Timestamp timestamp) {
String date = "";
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timestamp.getTime()));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
String monthstr = "";
String daystr = "";
if(month<10)
monthstr = "0"+month;
else
monthstr = ""+month;
if(day<10)
daystr = "0"+day;
else
daystr = ""+day;
date = year + "-" + monthstr + "-" + daystr ;
return date;
}
To reverse data to database:
public static Timestamp getFechaStringToTimestamp (String strDate) {
Timestamp timestamp = null;
strDate = strDate + " 00:00:00";
timestamp = Timestamp.valueOf(strDate);
return timestamp;
}

How to replace date part to current date in existing date object

I have a date object parsed from JSON in the follwing format:
String date = getJsonDateFromServer();
Date result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(date);
But I am only interested in the time part (no months, year, day etc).
So my question is: How do I replace the date part (Months, Year, Day) correctly without loosing the time zone information?
What I finally want to do is the following:
(1) Parsing two dates (without date information). Start and Endtime
(2) Check for another date 'dw' (with date information) if 'dw' is in between the time defined in start and end from (1)
For example:
Date start = parse(18:00 +02:00);
Date end = parse(20:00 +02:00);
Date dw=new Date();
boolean inBetween = dw>= start && dw <= end;
How to do this?
/UPDATE:
I implemented it for test purposes this way:
public boolean isActiveOn(Date date) {
Calendar toCheck = Calendar.getInstance();
toCheck.setTime(date);
Calendar cal_start = Calendar.getInstance();
cal_start.setTime(this.time_begin);
cal_start.set(toCheck.get(Calendar.YEAR), toCheck.get(Calendar.MONTH),
toCheck.get(Calendar.DAY_OF_MONTH));
Calendar cal_end = Calendar.getInstance();
cal_end.setTime(this.time_end);
cal_end.set(toCheck.get(Calendar.YEAR), toCheck.get(Calendar.MONTH),
toCheck.get(Calendar.DAY_OF_MONTH));
boolean after_start = toCheck.after(cal_start);
boolean before_end = toCheck.before(cal_end);
return after_start && before_end;
}
But isn't that causing problems when different timezones are set in this.time_begin, this.time_end and date ?
All you have to do is:
String date = getJsonDateFromServer();
Date result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(date);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ssZ")
Date timeOnly = dateFormat.parse(dateFormat.format(result));
Now you have a date with time and timezone only.
And here is the compare code:
Date start = dateFormat.format(result);
Date end = dateFormat.format(resultNr2);
Date dw = dateFormat.format(resultNr3);
boolean inBetween = dw.after(start) && dw.before(end);
private DatePickerDialog createDialogWithoutDateField(){
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
(AdditionalRepaymentDetailClass.this, datePickerListener_edtToDate,mYear,mMonth, mDay);
DatePickerDialog edtToDate= new DatePickerDialog(DirectDebitClass.this, datePickerListener_edtToDate, year, month,day);
try{
Field[] datePickerDialogFields = edtToDate.getClass().getDeclaredFields();
for (Field datePickerDialogField : datePickerDialogFields) {
if (datePickerDialogField.getName().equals("mDatePicker")|| datePickerDialogField.getName().equals("mDaySpinner")) {
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField.get(edtToDate);
Field datePickerFields[] = datePickerDialogField.getType().getDeclaredFields();
for (Field datePickerField : datePickerFields) {
if ("mDayPicker".equals(datePickerField.getName())|| "mDaySpinner".equals(datePickerField.getName())) {
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}
}
}
}
}catch(Exception ex){
}
return edtToDate;
}
U can try this

Categories

Resources