Given LocalDate I want to convert to week number since Epoch
One way to do that is:
LocalDate date = datePicker.getValue(); // input from your date picker
Locale locale = Locale.US;
int weekOfYear = date.get(WeekFields.of(locale).weekOfWeekBasedYear());
And X = find weeks since Epoch to prevYear
And then result = X + weekOfYear
Although someway we can find out "week number since epoch", is there clean solution to find it using Java 8 ?
UPDATE: Even above solution wont work as one week(always starting from Sunday) can span across two years
There's a method out there for milliseconds since epoch for a
Date
:and apparently there are 604800000 milliseconds to a week. So I guess you could go
I think you'd probably actually need to add 1 to your final value though, since Java truncates
long
s.I am turning the comment by Tunaki into an Answer.
tl;dr
LocalDate
The
LocalDate
class represents a date-only value without time-of-day and without time zone.A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Here we use UTC as the time zone for today’s date, in accordance with the epoch being defined in UTC.
ChronoUnit
The
ChronoUnit
class has methods for calculating an elapsed number of years or months or weeks or such. For weeks it simply takes the number of days and divides by 7. So the first day-of-week is irrelevant. Not sure if that meets your needs or not as the Question is vague.Dump to console.
You could adjust your starting date to a specific day-of-week if that makes sense for your needs. I'm not sure if that fits because the Question is not clear.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.