Date picker first and last day of previous - java

Could someone please help me in finding from datepicker first and last day of previous month.
Achieved to pickup current date and 1st of current month, with following:
// Choose today's date
String today = LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM-YYYY"));
driver.findElement(By.xpath("//*[#id=\"viewPeriodStart\"]")).clear();
driver.findElement(By.xpath("//*[#id=\"viewPeriodStart\"]")).sendKeys(today);
//Choose first of a month
String firstDayinMOnth = LocalDate.now().format(DateTimeFormatter.ofPattern("01/MM-YYYY"));
driver.findElement(By.xpath("//*[#id=\"viewPeriodEnd\"]")).clear();
driver.findElement(By.xpath("//*[#id=\"viewPeriodEnd\"]")).sendKeys(firstDayinMOnth + Keys.ENTER);
Thread.sleep(8000);
driver.findElement(By.xpath("//*[#id=\"calenderShowHide\"]/div/input[3]")).click();
But have no idea how to create 1st and last of previous month.
Thank you in advance

Solved, after a bit of Googling & checking:
String lastDay = LocalDate.now().withDayOfMonth(1).minusDays(1).format(DateTimeFormatter.ofPattern("dd/MM-YYYY"));
String firstDay = LocalDate.now().withDayOfMonth(1).minusDays(1).withDayOfMonth(1).format(DateTimeFormatter.ofPattern("dd/MM-YYYY"));

These points were not what you asked, but I believe they are still helpful suggestions for you.
Consider half-open intervals.
Read LocalDate.now() only once for consistency.
Give your desired time zone.
Don’t use uppercase YYYY in your format pattern string.
Half-open: It’s natural to think of the days of a month as being from the first of the month to the last day of the month inclusive. However, a standard handling would go from the first of the month inclusive to the first of the next month exclusive. It’s still the same days, only a different representation. Particularly when you handle successive months this gives simplicity and prevents errors: when you have the first of this month, you don’t also need the last of the previous month. And there’s no way you could make a gap between the two periods by mistake.
Read today’s date only once. If your code happens to run across midnight, you may accept that you cannot control whether it uses the date from before 0:00 or the date after, but you want to make sure it doesn’t use both for the different date calculations, or you risk inconsistent dates, like all the dates belonging to the same month rather than last month and this month.
Give a time zone: It is never the same date in all time zones on Earth. So a time zone is needed for determining today’s date or just current month. Make that explicit. Even if you want ZoneId.systemDefault(), write that to force yourself into making a conscious decision and to tell the reader that you have done so.
LocalDate today = LocalDate.now(ZoneId.of("Europe/Belgrade"));
LocalDate firstDayOfCurrentMonth = today.withDayOfMonth(1);
LocalDate lastDayOfCurrentMonth = today.with(TemporalAdjusters.lastDayOfMonth());
YearMonth lastMonth = YearMonth.of(today.getYear(), today.getMonth())
.minusMonths(1);
LocalDate firstDayOfLastMonth = lastMonth.atDay(1);
LocalDate lastDayOfLastMonth = lastMonth.atEndOfMonth();
A YearMonth is a month in the calendar like April 1940 or February 2018. A year and a month. I am deliberately being a bit inconsistent in the code. In production code you would probably want to handle either this and last month through YearMonth objects or none of them. But I am showing you both options so you can make your pick. Use YearMonth.now(ZoneId) if you want current month.
Final point: YYYY in the format pattern string. Here’s a correct version of your formatter:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM-uuuu");
If instead of today I run my code next January and use a formatter with uppercase YYYY, I get the previous month as 01/12-2018 through 31/12-2019. It should have been 31/12-2018, but that date belongs to week 1 of 2019, which is what YYYY gives you. Instead use uuuu or lowercase yyyy.

Related

Selenium add weekdays to a date, weekend days not calculated correctly

I am running the below code on 6/7/2018 in order to omit weekends from any dates returned. However the code seems to determine the below days as the weekend.
13/7/2018 - Friday & 14/7/2018 - Saturday
rather than
14/7/2018 - Saturday & 15/7/2018 - Sunday
I am updating the field indicated to increase / reduce the amount of days in the future I want to select.
If I input 5 days the date returned is 12/7/2018 and if I input 6 days the date returned is 15/7/2018.
Is there something obvious I am missing, any help would be much appreciated.
Date date=new Date();
Calendar calendar = Calendar.getInstance();
date=calendar.getTime();
SimpleDateFormat s;
s=new SimpleDateFormat("dd/MM/yyyy");
System.out.println(s.format(date));
int days = 5; //I am updating this value to increase and decrease days
for(int i=0;i<days;)
{
calendar.add(Calendar.DAY_OF_MONTH, 1);
//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(calendar.get(Calendar.DAY_OF_WEEK)<=5)
{
i++;
}
}
date=calendar.getTime();
s=new SimpleDateFormat("dd/MM/yyyy");
System.out.println(s.format(date));
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.UK);
LocalDate date = LocalDate.now(ZoneId.of("Pacific/Truk"));
System.out.println(date.format(dateFormatter));
int days = 5;
int i = 0;
while (i < days) {
date = date.plusDays(1);
DayOfWeek day = date.getDayOfWeek();
if (! day.equals(DayOfWeek.SATURDAY) && ! day.equals(DayOfWeek.SUNDAY)) {
i++;
}
}
System.out.println(date.format(dateFormatter));
Output today (Sunday 8th July):
08/07/2018
13/07/2018
13th July is next Friday, so obviously it didn’t take Friday as weekend.
Is there something obvious I am missing(?)
It don’t think it’s that obvious: The Calendar class numbers the days of the week from 1 for Sunday through 7 for Saturday. This comes from an American understanding of weeks. So when your condition was that the day of week should be less than or equal to 5, you included Sunday (1) through Thursday (5) and filtered out Friday (6) and Saturday.
…if you could point me in the right direction to the documentation…
To find this information in the documentation you would have to look under each constant for day of week, SUNDAY, etc., and there follow the link Constant Field Values. See the links at the bottom of this answer.
The Calendar class has proved poorly designed (despite attempts to fix the problems with Date) and is now long outdated too. Instead I recommend that you use java.time, the modern Java date and time API. Which I of course do in the snippet above.
One of many problems with Calendar is the use of int for day of week (and other items that have names rather than being numbers). It’s unnatural and very easy to confuse. One may say that you reinforced the problem by comparing to 5 rather than to Calendar.FRIDAY, but because of the American numbering the latter wouldn’t have solved your issue either. java.time’s DayOfWeek is an enum and doesn’t invite for comparing using “less than” or “is before” (though you may, and it would work in your case). The code referring to named constants SATURDAY and SUNDAY is not only clearer to read, it is also less error-prone.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Documentation of LocalDate and DayOfWeek
Calendar.SUNDAYdocumentation
Constant Field Values documentation

Getting wrong date when I add months

I am writing my stubs in StubbyDB. And asserting the data in functional tests. This is something I am doing in my functional tests to calculate date for assertion (using joda datetime library)
DateTime now = DateTime.now();
DateTime future = now.plusMonths(6);
And this is something I am doing in my stubs;
{{TODAY+6m}}
But I am getting the difference of few days. Is this the bug or am I doing something wrong?
Edit
Consider today is "30 Sept 2016", and I add 5 months to it then
now.plusMonths(5) => 2017-02-28
{{TODAY+5m}} => 2017-03-02
Reason
As per joda-time documentation,
2007-03-31 plus one month cannot result in 2007-04-31, so the day of
month is adjusted to 2007-04-30.
However StubbyDB use javascript based date calculation which adjust date 2007-04-31 to 2007-05-01.
So this is not the bug but this is how these APIs work.
Solution
Found in sample application
use {{JODA_TODAY+6m}} instead of {{TODAY+6m}}
if you start with 30/09/2016 and add five months you get 30/02/2017.
But February only has 28 days.
It looks like Jodatime has "rounded down" to give you the maximum valid date for the month (i.e 28th Feb) whereas the other library/code is treating "30th Feb" as 2nd March (since that is technically two days past the 28th, which the 30th would also be).
Both are valid assumptions for handling dates IMHO and are a good lesson in why date handling is hard. You'll need to be explicit about which convention you want to follow and you may have to code your assertions to follow Jodatime's conventions.
See: DateTime::plusMonths(int)
Returns a copy of this datetime plus the specified number of months.
The calculation will do its best to only change the month field
retaining the same day of month. However, in certain circumstances, it
may be necessary to alter smaller fields. For example, 2007-03-31 plus
one month cannot result in 2007-04-31, so the day of month is adjusted
to 2007-04-30.
So, 30 Sept 2016 + 5 months = 28 Feb 2017 (according to Joda's logic) and it is not a bug
Here is sample code for adding months to given calendar date
public class Demo {
// create a calendar
Calendar cal = Calendar.getInstance()
// print current date
System.out.println("The current date is : " + cal.getTime());
// add 1 months from the calendar
cal.add(Calendar.MONTH, 1);
}
FYR How to add one month to a date and get the same day

Obtaining correct Joda LocalDateTime values and then formatting them

I am trying to run a report every Sunday at midnight that will include data from the previous Saturday at midnight, to 11:59:59 just prior to the report kicking off. Hence, if it were to get kicked off this coming Sunday (2/17), it would:
Execute at 2/17/2013 at midnight (or Monday morning, however you like to think of it)
Include data starting at 2/10/2013 12:00:00 AM (last Saturday midnight)
Include data up to 2/16/2013 11:59:59 PM (this Saturday night, just 1 second prior to the report firing)
I'm trying to obtain a startDateTime and endDateTime to encapsulate the time range, and want to use a JODA LocalDateTime to hold each value. I then need to format them into YYYYMMDD_HHmmss-formatted strings.
Here's my best attempt:
LocalDateTime rightNow = new LocalDateTime();
LocalDateTime startDateTime = rightNow.minusDays(7);
LocalDateTime endDateTime = rightNow.minusDays(1);
String startDateTimeFormatted = startDateTime.toString();
String endDateTimeFormatted = endDateTime.toString();
System.out.println(startDateTimeFormatted);
System.out.println(endDateTimeFormatted);
When I run this I get:
2013-02-06T12:10:27.411
2013-02-12T12:10:27.411
Note: since I'm running this code today (2/13/2013) the start/end dates are different then they would be on Sunday 2/17 (or any other Sunday), but its the time representation and the String formatting I'm really interested in here.
So I ask:
How to get startDateTime to represent (for this example - but I need the answer to be dynamic!) 2/10/2013 12:00:00 AM
How to get endDateTime to represent (for this example - but I need the answer to be dynamic!) 2/16/2013 11:59:59 PM
How to format both startDateTime and endDateTime to appear as 20130210_120000 and 20130216_115959 respectively?
Thanks in advance.
Okay, as mentioned before, I would strongly recommend using UTC as the time zone, and an exclusive end point. So, you can use:
private static final DateTimeFormatter FORMATTER =
DateTimeFormat.forPattern("yyyyMMdd'_'HHmmss")
.withLocale(Locale.US);
...
// I prefer to be explicit about using "the current time". I prefer to use
// an injectable dependency such as a Clock type, too...
DateTime now = new DateTime(System.currentTimeMillis(), DateTimeZone.UTC);
// Note: this *doesn't* ensure that it's the right day of the week.
// You'd need to think about that separately - it may be as simple as
// scheduling it appropriately... but bear your local time zone in mind!
DateTime end = now.withTimeAtStartOfDay();
DateTime start = end.minusDays(7);
String startText = FORMAT.print(start);
String endText = FORMAT.print(end);
Further note that this will use a 24-hour clock, so it would give 20130210_000000 and 20130217_000000 rather than using 120000 as the time. This is far more consistent and unambiguous. Given that it's always midnight though, you might want to just use yyyyMMdd and remove the time part entirely.
System.out.println(DateTime.now().toString("yyyy-MM-dd"));
the toString method accepts a formatting template, see: http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html

Java check if date is next sunday

I get a date and want to check if it is the next sunday.I found alot of code with Calendar etc, but I can't find the right code. And I don't really understand how I can know if it is the next sunday from a date.
Thanks for you help
Break the problem down:
Get today's date: new Date();
Get the day of the week for today's date.
Advance forward to Sunday
Get that date
First of, I recommend Joda Time as a much better Date/Time API than Calendar.
As for your processing it breaks down into easy steps:
Construct DateTime objects for the two dates
Check that the target date is a Sunday
Check that the difference between them is between 0 and 7 days
If you look for nice Date management, check this out Joda Time
this might be helpful to you , you can chek by dayOfWeek == Calendar.SUNDAY after adding one day
With Lamma Date it's very easy to first obtain next Sunday, then we can use equals check if the date is next Sunday.
Date today = new Date(2014, 7, 1); // assume today is 2014-07-01
Date nextSunday = today.next(DayOfWeek.SUNDAY); // 2014-07-06

Is it possible to get the previous day of the week using Joda-Time?

I am new to Joda-Time and was looking at getting the previous working/week day.
My initial try was done on a Monday and I wanted to get the date for T -1 which will be Friday:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
Chronology coptic = GJChronology.getInstance(zone);
DateTime dt = new DateTime(coptic);
DateTime minusOneDay = dt.minusDays(1);
System.out.println(minusOneDay );
But as I expected returns the date on Sunday. Does anyone know how to get the previous week day?
Thanks in advance..
This doesn't look to be handled by Joda time.
There is a sourceforge project that looks to handle it though.
objectlabkit
If the day is Monday or Sunday, then you need to subtract three or two days respectively. In all other cases subtract one day. This assumes a working week from Monday to Friday (which doesn't apply to all cultures).

Categories

Resources