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
I am turning the comment by Tunaki into an Answer.
tl;dr
ChronoUnit.WEEKS.between (
LocalDate.ofEpochDay ( 0 ) ,
LocalDate.now( ZoneOffset.UTC )
)
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.
LocalDate today = LocalDate.now( ZoneOffset.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.
LocalDate today = LocalDate.now ( ZoneOffset.UTC ); // Using UTC to match the definition of the Java epoch.
LocalDate epoch = LocalDate.ofEpochDay ( 0 );
long weeks = ChronoUnit.WEEKS.between ( epoch , today );
Dump to console.
System.out.println ( "epoch: " + epoch + " | today in UTC: " + today + " | weeks: " + weeks );
epoch: 1970-01-01 | today in UTC: 2016-08-29 | weeks: 2434
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.
LocalDate epoch = LocalDate.ofEpochDay ( 0 );
LocalDate start = epoch.with ( TemporalAdjusters.nextOrSame ( DayOfWeek.SUNDAY ) ); // Get the first Sunday that *is* the epoch or *follows* the epoch.
long weeks = ChronoUnit.WEEKS.between ( start , today );
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?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
There's a method out there for milliseconds since epoch for a Date:
long timeInMillis = date.getTime();
and apparently there are 604800000 milliseconds to a week. So I guess you could go
long weeksSinceEpoch = date.getTime() / 604800000;
I think you'd probably actually need to add 1 to your final value though, since Java truncates longs.
Related
I am writing an application and have to convert a string into date. The string will have weeks, days and other information, and finally calculate time difference in minutes from that date to current time as shown below. With the code I have, I was expecting to have the "past" object as certain calendar date that was "13 weeks, 2 days, 16 hours, 42 minutes" from current time but what I found surprised me (date object is Tue Mar 24 15:54:00 CST 1970 as of now). Can some one please explain me why my code doesn't work and how to fix that? I referred to the Java Docs but it didn't help me much.
String givenStr = "13 weeks, 2 days, 16 hours, 42 minutes";
SimpleDateFormat format = new SimpleDateFormat("w 'weeks', u 'days', H 'hours', m 'minutes'");
try {
Date past = format.parse(givenStr);
Date now = new Date();
Long minutes = (now.getTime()-past.getTime())/(60*1000);
System.out.printf("Date: %s Minutes: %s\n", past, minutes);
} catch (ParseException ex) {
//DO STH
}
tl;dr
Use standard ISO 8601 formatting for your span-of-time text: P13W2DT16H42M.
Use modern date-time classes found in the java.time framework and in the ThreeTen-Extra library: Instant, PeriodDuration, and Duration.
Instant
.now()
.plus(
PeriodDuration
.parse(
"P" +
"13 weeks, 2 days, 16 hours, 42 minutes"
.replace( " weeks, " , "W" )
.replace( " days, " , "DT" )
.replace( " hours, " , "H" )
.replace( " minutes" , "M" )
)
)
2019-08-18T18:30:42.007034Z
Details
You are conflating two different concepts:
a moment, a point on the timeline
a span-of-time unattached to the timeline
Moment
For a moment, we no longer use the java.util.Date class. That terrible class was supplanted years ago by the java.time.Instant class.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Span-of-time
Your input string does not represent a moment. It represents a span-of-time.
For a span in terms of years-month-days, we use the Period class. For a span in terms of hours-minutes-seconds, we use the Duration.
PeriodDuration
You can combine the two concepts using the PeriodDuration class found in the external library built from the ThreeTen-Extra project. But you should think twice about this. It rarely makes practical sense to combine the two granularities.
But, if you insist, let's give it a go.
First, alter your input string to use standard ISO 8601 format of PnYnMnDTnHnMnS. In this format, the P marks the beginning, and the T separates the coarser granularity from the finer.
String input = "P" + "13 weeks, 2 days, 16 hours, 42 minutes".replace( " weeks, " , "W" ).replace( " days, " , "DT" ).replace( " hours, " , "H" ).replace( " minutes" , "M" ) ;
P13W2DT16H42M
Parse that new input as a PeriodDuration.
PeriodDuration pd = PeriodDuration.parse( input );
Capture the current moment in UTC.
Instant now = Instant.now();
now.toString(): 2019-05-17T01:48:42.007034Z
Add your period-duration to determine a future moment.
Instant later = now.plus( pd );
later.toString(); 2019-08-18T18:30:42.007034Z
If you want a past moment rather than a future moment, call Instant::minus.
Instant earlier = now.minus( pd ) ;
Minutes elapsed
If you want a total number of minutes elapsed between those two moments, use Duration class.
Duration d = Duration.between( now , later ) ;
long minutesTotal = d.toMinutes() ;
minutesTotal: 134922
Time zone
If you want to work with a moment as perceived through the wall-clock time used by the people of a particular region (a time zone), use the ZonedDateTime and ZoneId classes. Call the same named plus/minus methods as seen above.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
ZoneDateTime earlier = now.minus( pd ) ;
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
I know how to get the milliseconds for a date after 1.1.1970. But how can I get the milliseconds for a specific date that occurs before that date?
I need that in an android app.
Thanks!
All numbers are signed in java, so all numbers can be negative. Therefore you can have a date with a negative amount of milliseconds. Therfore dates with a timestamp which is less than 0 is definitely possible.
You can know the earliest possible date by performing:
new Date(Long.MIN_VALUE)
You'll find that this returns a date which is more than 292 million years ago. This is even before the jurassic era. So there really isn't a need to worry about dates before 1970 :)
Using java.time.Instant, get your date in the Instant and you can use the getEpochSecond() method to return the number of seconds before the Epoch and just convert from that.
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html for more details about the Instant class.
tl;dr
LocalDate.of( 1953 , 1 , 17 )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
.toInstant()
.toEpochMilli()
…yields a negative number:
-535057200000
Details
As the other Answers said:
(a) In representing moments as a count-from-epoch-reference-date, moments before the epoch use negative numbers, moments after the epoch use positive numbers.
(b) You should be using java.time classes rather than the troublesome old date-time classes that are now legacy. See below for info on back-port to Android.
Using java.time
Use LocalDate for a date-only value, with no time-of-day nor time zone.
LocalDate ld = LocalDate.of( 1953 , 1 , 17 );
To convert to a moment, let's get the first moment of the day on that date. That means specifying a time zone, as the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ld.atStartOfDay( z );
Extract an Instant, a moment on the timeline in UTC.
Instant instant = zdt.toInstant();
From the Instant, extract the number of milliseconds since the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00Z). Beware of data-loss, as the java.time classes can hold a moment with a resolution of up to nanoseconds; asking for milliseconds means lopping off any nanoseconds if present.
long epochMillis = instant.toEpochMilli();
See this code run line in IdeOne.com.
ld.toString(): 1953-01-17
zdt.toString(): 1953-01-17T00:00-05:00[America/Montreal]
instant.toString(): 1953-01-17T05:00:00Z
epochMillis: -535057200000
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.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The problem was something I cannot reproduce. Before 1.1.1970 the values are negative. Now, my program calculates right, but I think, I didn't change something in the code. Maybe it was a cached version, which caused the problems. Thanks for all answers!
So, I'm trying to basically take 2 DateTime objects and set them to the first day of their respective months so that I can ultimately calculate the months between the two dates.
Example of the code:
DateTime dt = new DateTime();
DateTime newDT = dt.withDayOfMonth(1);
And before anyone asks, the actual code coverts a Date object into a DateTime object which is used in another section of the code.
The issue is, when I do this in a unit test it seems to work just fine. However, when I try to test this using SOAP UI I can see in the course of debugging that I'm getting a runtime exception due to:
method lookup failed for selector "withDayOfMonth" with signature "(I)Lorg/joda/time/DateTime;"
In the corresponding server.txt log file, I can see a stack trace which indicates a no such method has occured.
After further research, I've found that our app server currently employs an outdated version of the JodaTime jar (1.2.1), while my eclipse library contains the correct jar (1.6.2).
However, now the question becomes what's the best way to accomplish my goal here (to create a new DateTime object with the first day of the month set to 0) since I don't have access to the withDayOfMonth method provided by JodaTime?
tl;dr
LocalDate firstOfThisMonth =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.with( TemporalAdjusters.firstDayOfMonth() ) ;
Details
Other answers address your Joda-Time question. However, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. So here is a solution in java.time code.
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.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
TemporalAdjuster
The TemporalAdjuster interface in java.time provides for classes to manipulate a value. The TemporalAdjusters class (note the plural s) provides several handy implementations of adjusters. One is firstDayOfMonth.
LocalDate firstOfThisMonth = today.with( TemporalAdjusters.firstDayOfMonth() ) ;
firstOfThisMonth.toString(): 2016-03-01
Period
The Period class tracks a span of time not attached to the timeline. It keeps a number of years, months, and days.
LocalDate start = LocalDate.of ( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of ( 2016 , 3 , 1 ) ;
Period p = Period.between ( start , stop ) ;
Calling toString on a Period generates a string in standard ISO 8601 format.
P2M
You can ask for one part as a number, such as number of months.
int months = p.getMonths();
2
Note that the elapsed time shown here wisely uses the Half-Open approach where the beginning is inclusive while the ending is exclusive.
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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
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.
A possible way to do so, using another method for Joda-Time API which is present in 1.2.1 version it's the follow:
DateTime dateTime = new DateTime().dayOfMonth().withMinimumValue();
Another approach could be to use jdk Calendar to set the first day of the month for a date. And then get the joda DateTime using DateTime(Calendar cal) constructor:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
DateTime dateTime = new DateTime(cal);
However probably as other answer suggest the best you can do is update your Joda-Time version.
Calculate months from difference of the two month values. For example if newDate is 1st July 2016 and oldDate is 31st May 2016, newDate.getMonth() will return 7 and oldDate.getMonth() will return 5, and the difference will be rounded up as required.
int months = newDate.getMonth() - oldDate.getMonth(); // 7 - 5 = 2
I would like to have a class to represent a particular week of year - for example today it's 29 November, which is exactly week number 48 of year 2014. So, one example implementation would be:
import java.time.Year;
public class WorkingWeek {
private int weekNumber;
private Year year;
}
Another conception is to have just a week's Monday date in a WorkingWeek class, but I feel it's less intuitive and I will frequently use week-in-year number.
Is there a class in Java 8 Time API that would fit best my requirements? Or if not, what would be recommended approach?
You need to specify your definition of a week.
String Representation Of A Year-Week
One option is strings. The ISO 8601 standard defines a week as beginning on a Monday, ending on Sunday, with the first week of the year being the first to contain a Thursday, resulting in 52 or 53 weeks a year.
The standard also defines a string representation for this week-of-year span of time in the format of YYYY-Www (or omitting hypen, YYYYWww) such as 2014-W07. A day within the week is represented by a digit where Monday is 1 and Sunday is 7, in the format YYYY-Www-D (or omitting hyphen, YYYYWwwD) such as 2014-W07-2 (a Tuesday in 7th week of year). The W is important to disambiguate from a year-month such as 2014-07 being July of 2014.
java.time
The java.time package built into Java 8 and later is inspired by Joda-Time but entirely re-architected. See Tutorial.
In java.time, an Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime. Use LocalDate to get a date-only value with no time-of-day and no time zone.
Note that determining the first moment of a day in java.time requires an extra step when compared to Joda-Time: We must go through the LocalDate class to call its atStartOfDay method.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
LocalDate firstDayOfThisWeek = now.toLocalDate ().with ( DayOfWeek.MONDAY );
LocalDate firstDayOfNextWeek = firstDayOfThisWeek.plusWeeks ( 1 );
ZonedDateTime thisWeekStart = firstDayOfThisWeek.atStartOfDay ( zoneId );
ZonedDateTime nextWeekStart = firstDayOfNextWeek.atStartOfDay ( zoneId );
Unfortunately, java.time lacks the equivalent of Joda-Time's Interval.
Fortunately we have ThreeTen Extra, the project that extends java.time (310 being the number of the JSR defining java.time). This library includes an Interval class that integrates with java.time. This Interval class is more limited than that of Joda-Time as it supports only Instant objects without time zones (always in UTC).
Caution: The ThreeTen-Extra project reserves the right to change its interfaces and/or implementations. While intended to be useful as-is, it also serves as an experimental proving ground for classes that may be eventually incorporated into java.time. I gladly make use of ThreeTen-Extra, but you must make your own risk-benefit decision.
// This next line requires adding the `ThreeTen Extra` library to your project.
Interval interval = Interval.of ( thisWeekStart.toInstant () , nextWeekStart.toInstant () ); // "Interval" is part of ThreeTen-Extra project, not built into Java 8.
Dump to console.
System.out.println ( "now: " + now + " thisWeekStart: " + thisWeekStart + " nextWeekStart: " + nextWeekStart + " interval: " + interval );
now: 2016-01-15T18:10:48.143-05:00[America/Montreal] thisWeekStart: 2016-01-11T00:00-05:00[America/Montreal] nextWeekStart: 2016-01-18T00:00-05:00[America/Montreal] interval: 2016-01-11T05:00:00Z/2016-01-18T05:00:00Z
You can determine the week-of-year as defined by the ISO 8601 standard. Note the "week based" terms. Near the beginning or ending of the year, a date will be in one calendar year while its ISO 8601 week’s year may be ±1.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
int weekOfYear = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekBasedYear = now.get ( IsoFields.WEEK_BASED_YEAR );
System.out.println ( "weekOfYear: " + weekOfYear + " of weekBasedYear: " + weekBasedYear );
weekOfYear: 2 of weekBasedYear: 2016
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?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode and advises migration to the java.time classes. I am leaving this section intact as history.
The Joda-Time 2.5 library offers the Interval class to represent a span of time as a pair of specific moments in time along the timeline of the Universe. Each moment is represented by the DateTime class.
Half-Open
Joda-Time uses the Half-Open [) approach to defining spans of time. The beginning is inclusive while the ending is exclusive. This is generally the best way to work with such spans of time. Search StackOverflow for many examples and discussions.
ISO 8601 in Joda-Time
Joda-Time uses the ISO 8601 definition of weeks. Also, Joda-Time uses ISO 8601 as its defaults for parsing and generating string representations of date-time values.
DateTimeZone zone = DateTimeZone( "America/Montreal" );
// Get first moment of a Monday. Inclusive.
DateTime start = new DateTime( 2014, 11, 24, 0, 0, 0, zone ); // Handle exception thrown if occurring during a Daylight Saving Time gap.
DateTime stop = start.plusWeeks( 1 ); // First moment of following Monday. Exclusive.
Interval week = new Interval ( start, stop );
First Monday
Search StackOverflow for many questions and answers on finding the first Monday of a week.
LocalDate (date-only)
While you might well be tempted to use LocalDate objects (date only, no time-of-day) to build an Interval. That would be sensible and useful. Unfortunately, the implementation of Interval supports only DateTime objects, not LocalDate.
YearWeek Class
The ThreeTen-Extra project has a class for YearQuarter. The original question looks like it is asking for a YearWeek class. Work has been done to add such a class to ThreeTen-Extra.
Another possibility is to use the class CalendarWeek in my library Time4J. Example:
CalendarWeek now = SystemClock.inLocalView().now(CalendarWeek.chronology());
int actual = now.getWeek(); // 35 on 2016-08-29
int max = now.getMaximum(CalendarWeek.WEEK_OF_YEAR); // 52 in year 2016
This class is also modelled as date interval and can be converted to a common DateInterval (from Monday to Sunday) offering stream support via its method toFlexInterval().
How to get Unix timestamp value only for particular year.
I have a situation where in server side for DOB i store only year. So in android i take Age value and then subtract current year with the age and send that year to server. To send that year i need to convert to Unix timestamp because in server side it stores in Unix timestamp format.
Somebody please help what can be done. I saw some links which uses getTime() and divide it by 1000. But that would be whole year with date and month.
Try this:
Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, theYear); // Set the year you want
myCal.set(Calendar.DAY_OF_YEAR, 1);
myCal.set(Calendar.HOUR, 0);
myCal.set(Calendar.MINUTE, 0);
Date theDate = myCal.getTime();
java.time
I get current year and i am converting it to integer and then age which user enters. For example, current year is 2014 and he puts age as 20 so his dob year is 1994. I wanted timestamp value of 1994. And i wanted in GMT.
Apparently you want to the moments at each end of a year.
The modern solution uses the java.time classes that supplanted the terrible old legacy date-time classes.
Parse integer from string
First the year.
String input = "20" ;
integer age = Integer.parseInt( input ) ;
Time zone
Determining a date, and therefore a year, requires a 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.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your [desired/expected time zone][2] explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Year
Get the current year.
Year currentYear = Year.now( z ) ;
LocalDate & ZonedDateTime
Get the first day of the year as a LocalDate. From that, get the first moment of the day as a ZonedDateTime. A day does not always start at 00:00, so let java.time determine the first moment.
LocalDate firstOfYear = currentYear.atDay( 1 ) ;
ZonedDateTime yearStart = firstOfYear.atStartOfDay( z ) ;
Half-Open
Use Half-Open approach to defining a span-of-time, where beginning is inclusive while the ending is exclusive.
LocalDate firstOfFollowingYear = currentYear.plusYears( 1 ).atDay( 1 ) ;
ZonedDateTime yearStop = firstOfFollowingYear.atStartOfDay( z ) ;
Count-from-epoch
You do not specify what you mean exactly by “Unix timestamp”. I will guess you mean a count of whole seconds since the epoch reference of first moment of 1970 in UTC.
long start = yearStart.toEpochSecond() ;
long stop = yearStop.toEpochSecond() ;
For more discussion, see my Answer to a similar Question.
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?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.