How to find first sunday of next month in Java 8? - java

I searched on StackOverflow for the same, but all the answers are for legacy java versions.
I did not find any of the answers with Java 8 Data and Time utility.
Can anybody help me out for the same?

I find out a way using LocalDate and TemporalAdjuster's with() method as follows:
LocalDate firstSundayOfNextMonth = LocalDate
.now()
.with(firstDayOfNextMonth())
.with(nextOrSame(DayOfWeek.SUNDAY));

Related

Offset not calculated correctly at OffsetDateTime to Instant conversion in Java 8 [duplicate]

This question already has answers here:
ZonedDateTime America/Phoenix zone to GMT having issue [duplicate]
(3 answers)
Java Date Time conversion to given timezone
(3 answers)
Closed 7 months ago.
I would need the community's help because I could not find the answer in the Java documentation. I don't understand how the offset is taken into the math calculations when I try to convert an OffsetDateTime (ex: 2022-07-09T11:30:34) object to an Instant object. For example:
If we would run on OpenJDK 1.8 the command in a main function: OffsetDateTime.parse("2022-07-09T12:30:34+01:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME).toInstant() the outcome would be an Instance of date-and-time 2022-07-09T11:30:34 when I would had expected an Instant of 2022-07-09T13:30:34. The difference is the hour. Why do I get it like this?
And the opposite using -01:00 will do the revet.
I apologize for not formatting my text correctly or if I missed something. I would appreciate it if my post would not be marked us not worthy. And sorry if the answer was already answered in a different thread, which I could not find.
Thank you in advance.

Invalid ZoneDateTime parsing in Java / Scala [duplicate]

This question already has an answer here:
ZonedDateTime change behavior jdk 8/11
(1 answer)
Closed 2 years ago.
I am trying to parse dates from strings to ZonedDateTimes and I've come across a bizzare problem.
2020-11-01T01:00-05:00[America/New_York]
This is an hour right after time EDT ends this year. When I pass it to ZonedDateTime.parse I get
ZonedDateTime.parse("2020-11-01T01:00-05:00[America/New_York]")
// 2020-11-01T01:00-04:00[America/New_York]
but if I do
ZonedDateTime.parse("2020-11-01T01:00-04:00[America/New_York]").plusHours(1)
I get
2020-11-01T01:00-05:00[America/New_York]
So it's not like Java cannot represent this ambiguous value or something..
Can anyone explain to me that behavior and possible solution?
Note: I am using Java 8
As Amir Schnell said in the comments, this seems to be a bug in the JDK, as they cannot reproduce this in Java 11.
For now, I have found this work around:
Parse the string into a local date time, zone ID, and zone offset, and create a ZonedDateTime using those three things:
TemporalAccessor ta = DateTimeFormatter.ISO_ZONED_DATE_TIME.parse("2020-11-01T01:00-05:00[America/New_York]");
System.out.println(
ZonedDateTime.ofLocal(
LocalDateTime.from(ta),
ZoneId.from(ta),
ZoneOffset.from(ta)
)
);

Best way to increment the date in a String URL? [duplicate]

This question already has answers here:
How to add days to a date in Java
(3 answers)
Closed 7 years ago.
So I have a URL that contains date=2016-01-25 somewhere in between. My goal is, when a user enters the URL and n days (in a GUI application's text fields), it should go into a loop of n times and increment the date from the URL. That also means it goes to the next month if it is 30/31. Anyone have an optimized approach to this?
Assuming you are using Java 8, you can use the java.time.LocalDate class to parse, add days, and convert back to a string. Here's an example:
String date = "2016-01-25";
LocalDate localDate = LocalDate.parse(date);
localDate = localDate.plusDays(15);
System.out.println(localDate); // Prints "2016-02-09"
To add to the Java 8 solutions, if you're using an earlier version of Java you can use JodaTime's LocalDate class to accomplish the same thing. Syntax will be the same as in Java 8.
You would need to parse the date string out of the URL, using something like regex and then create a Date object increment your date and rebuild the URL.
Java's Date primitives such as LocalDate have support for "plusDays(int n)"

How to get 5 years before now

I am new to java 8 and I am trying to get five years before now, here is my code:
Instant fiveYearsBefore = Instant.now().plus(-5,
ChronoUnit.YEARS);
But I get the following error:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
Can anyone help me how to do that?
ZonedDateTime.now().minusYears(5).toInstant()
That will use your default time zone to compute the time. If you want another one, specify it in now(). For example:
ZonedDateTime.now(ZoneOffset.UTC).minusYears(5).toInstant()
According to the Javadoc, Instant will only accept temporal units from nanos to days Instant.plus(long amountToAdd, TemporalUnit unit);
You can use LocalDateTime. You use it the same way, but it will support operation on the YEARS level.
Instant does not support addition or subtraction of YEARS.
You can use this LocalDate if you only need date without time:
LocalDate date = LocalDate.now();
date = date.plus(-5, ChronoUnit.YEARS);
Otherwise you can user LocalDateTime.
I bumped into the same exception, but with ChronoUnit.MONTHS. It is a little bit misleading, because on compile time does not throw an error or warning or something.
Anyway, I read the documentation, too:
and, yes, all the other ChronoUnit types are not supported unfortunately.
Happily, LocalDateTime can substract months and years, too.
LocalDateTime.now().minusYears(yearsBack)
LocalDateTime.now().minusMonths(monthsBack);
If you are so inclined is does not require the date time conversion.
Instant.now().minus(Period.ofYears(5).getDays(),ChronoUnit.DAYS);

Get Week Number of LocalDate (Java 8) [duplicate]

This question already has answers here:
Get the weeknumber from a given date in Java FX
(4 answers)
Closed 8 years ago.
I'm trying to get the Week Number of a full LocalDate with the format:
dd.MM.yyy
I haven't found a function in the Java 8 Date API wich returns the Week Number and i have tried to create a algorithm, but it did'nt work.
One small warning. I haven't tested this yet, but looking at the API documentation of WeekFields and LocalDate.get, you should do something like:
LocalDate date = ...;
// Or use a specific locale, or configure your own rules
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int weekNumber = date.get(weekFields.weekOfWeekBasedYear());
The answer of Mark Rotteveel is almost right and again an example which kind of confusion potential there is in the class WeekFields (similar sounding method names, but deviating from intuitive civil usage). The right code requires another field:
LocalDate date = LocalDate.now();
TemporalField woy = WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear();
int weekNumber = date.get(woy);
See also the similar debate on this SO-post, especially the discussion and comments about the answer of #kleopatra.

Categories

Resources