Java check if date is next sunday - java

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

Related

Date picker first and last day of previous

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.

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

how to get the specific time in java [duplicate]

In my application there lies a code which works abruptly sometimes, its about getting a week interval using the java calendar object through Calendar.DAY_OF_WEEK.
The code checked for monday as start of week and sunday as end of week like:
fromCal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
toCal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
the toCal is set as the last sunday instead of coming sunday.
Is there any alternate way to do this other then this kind of hard coding.
Appriciate the help in advance.
Thanks,
Vaibhav
I guess you have to set the start of week to monday, otherwise last sunday IS the sunday of the week.
setFirstDayOfWeek
public void setFirstDayOfWeek(int value)
Sets what the first day of the week is; e.g., Sunday in US, Monday in France.
**Parameters:**
value - the given first day of the week.
Java Calender Doc
The issue is in locale. In English(US), Sunday is the first day of the week.
Check this code:
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("FirstDayOfWeek="+cal.getFirstDayOfWeek());
System.out.println(cal.getTime().toString());
cal = Calendar.getInstance(Locale.FRANCE);
System.out.println("FirstDayOfWeek="+cal.getFirstDayOfWeek());
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(cal.getTime().toString());
Be very clear on your desired behaviour here. You start with a calendar object whose "now" is some day of the week, perhaps "today". You the call set(DAY_OF_WEEK, ...). What effect do you desire if the Calendar's today is Tuesday? Sunday? Monday?
As observed in other answers, what happens depends upon the Calendar's opinion about what the First day of week is. So first set that to your chosen value. You will then (according to this answer get a Sunday and a Monday in the current week, which may not be what you want - what exactly do you need if today is Sunday? - some systems might actually be "thinking" about the next week.
Personally I might get my Monday according to some business rules and the get the Sunday after by adding 6 days.

Java Calendar using Calendar.DAY_OF_WEEK to get the first and the last dates for a particular date

In my application there lies a code which works abruptly sometimes, its about getting a week interval using the java calendar object through Calendar.DAY_OF_WEEK.
The code checked for monday as start of week and sunday as end of week like:
fromCal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
toCal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
the toCal is set as the last sunday instead of coming sunday.
Is there any alternate way to do this other then this kind of hard coding.
Appriciate the help in advance.
Thanks,
Vaibhav
I guess you have to set the start of week to monday, otherwise last sunday IS the sunday of the week.
setFirstDayOfWeek
public void setFirstDayOfWeek(int value)
Sets what the first day of the week is; e.g., Sunday in US, Monday in France.
**Parameters:**
value - the given first day of the week.
Java Calender Doc
The issue is in locale. In English(US), Sunday is the first day of the week.
Check this code:
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("FirstDayOfWeek="+cal.getFirstDayOfWeek());
System.out.println(cal.getTime().toString());
cal = Calendar.getInstance(Locale.FRANCE);
System.out.println("FirstDayOfWeek="+cal.getFirstDayOfWeek());
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(cal.getTime().toString());
Be very clear on your desired behaviour here. You start with a calendar object whose "now" is some day of the week, perhaps "today". You the call set(DAY_OF_WEEK, ...). What effect do you desire if the Calendar's today is Tuesday? Sunday? Monday?
As observed in other answers, what happens depends upon the Calendar's opinion about what the First day of week is. So first set that to your chosen value. You will then (according to this answer get a Sunday and a Monday in the current week, which may not be what you want - what exactly do you need if today is Sunday? - some systems might actually be "thinking" about the next week.
Personally I might get my Monday according to some business rules and the get the Sunday after by adding 6 days.

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