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.
Related
I have a method using 2 Instants in parameters getIssuesBillable(Instant start, Instant end, ....), my question is how I get the first day of a month and the last day of the month using a Java 8 Instant?
I already tried use withDayOfMonth(), and lengthOfMonth():
LocalDate initial = LocalDate.now();
LocalDate start = initial.withDayOfMonth(firstDayOfMonth());
LocalDate end = initial.withDayOfMonth(lastDayOfMonth());
But in this case, I need to convert and make some workarounds in this case, if someone knows a better way to do it I really appreciate any response.
tl;dr
Use modern java.time classes.
Here is a brief nonsensical example of starting with an Instant (a moment in UTC), assigning a time zone to view that moment through the wall-clock time used by the people of a particular region (a time zone), extracting the year-and-month as perceived in that time zone, and determining the first and last day of that month, rendering LocalDate objects.
YearMonth // Represent a year-and-month, the entire month as a whole.
.from( // Determine the year-and-month of some other date-time object.
Instant // Represent a moment in UTC.
.now() // Capture the current moment in UTC.
.atZone( // Adjust from UTC to a particular time zone.
ZoneId.of( "Pacific/Auckland" )
) // Returns a `ZonedDateTime` object.
) // Returns a `YearMonth` object.
.atDay( 1 ) // Returns a `LocalDate` object.
…or
…
.atEndOfMonth() // Returns a `LocalDate` object.
By the way, a realistic version of that particular code would be: YearMonth.now( ZoneId.of( "Pacific/Auckland" ) ).atDay( 1 )
Moment versus date-only
Instant is a moment in UTC, a date with time-of-day and an offset-from-UTC of zero.
A LocalDate is a date-only value, without time-of-day and without time zone.
You need to specify the time zone by which you want to perceive the date, the wall-clock time used by the people of a particular region.
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 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 3-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( "Africa/Casablanca" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract the date-only.
LocalDate ld = zdt.toLocalDate() ;
From there, proceed with your other code.
Or work with the month as a whole, using YearMonth class.
YearMonth ym = YearMonth.from( zdt ) ;
LocalDate first = ym.atDay( 1 ) ;
LocalDate last = ym.atEndOfMonth() ;
Tip: You might find helpful the LocalDateRange and Interval classes in the ThreeTen-Extra library.
Tip: Learn about the Half-Open approach to define a span of time, where the beginning is inclusive while the ending is exclusive. So a month starts on the first and runs up to, but does not include, the first day of the following month.
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.
For the first day of the month, depends on the time zone:
YearMonth.from(Instant.now().atZone(ZoneId.of("UTC"))).atDay(1);
For the last day of the month, depends on the time zone:
YearMonth.from(Instant.now().atZone(ZoneId.of("UTC"))).atEndOfMonth();
Postgresql returns day-of-week using EXTRACT with dow in the following fashion: 0 is Sunday, 1 is Monday, all the way to 6 which is Saturday, see official documentation.
I am looking for some official constants either in Java proper or in JDBC or perhaps some standard library (Apache Commons?) that match this numbering.
According to the same official documentation you should use isodow:
The day of the week as Monday (1) to Sunday (7)
tl;dr
I am looking for some official constants either in Java proper
Yes, Java defines the seven day-of-week values in the DayOfWeek enum using the same standard ISO 8601 definition as the isodow function in Postgres where a week runs from Monday-Sunday with days numbered 1-7.
DayOfWeek.WEDNESDAY.getValue() // Returns an `int` 1-7 for Monday-Sunday.
3
java.time.DayOfWeek enum
As the Answer by Rcordoval suggests, use the Postgres function isodow.
The “iso” in isodow refers to ISO 8601 standard and its definition of week where days are numbered 1-7 for Monday-Sunday.
Java supports that same definition of week in its DayOfWeek enum. That class defines seven objects for you, one for each day of the week such as DayOfWeek.MONDAY. To get each object’s day-of-week number, 1-7 for Monday-Sunday, call DayOfWeek::getValue. But in your Java coding, focus on using and passing around the DayOfWeek objects themselves rather than mere integer numbers.
int dowNumber = DayOfWeek.WEDNESDAY.getValue() ;
3
Going from the integer number to a DayOfWeek object is bit trickier, as we need to access a Java array using an index. The index means zero-based counting, so subtract one from your day-of-week number. Wednesday is day # 3, so subtract 1 for a result of 2 to access DayOfWeek.WEDNESDAY.
DayOfWeek dow = DayOfWeek.values()[ 3-1 ] ; // Get object named `WEDNESDAY` using zero-based index counting, so 3 - 1 = 2.
dow.toString(): WEDNESDAY
By the way, to automatically localize the name of the day-of-week, call DayOfWeek::getDisplayName.
Java rather than SQL
I am currently writing a query that is finding customers that currently have a Friday 10:00 AM in their respective time zone, so I need to pass in the concept of "Friday" into the query and of course I don't want to hard-code it.
May be better to do this work in Java using the industry-leading java.time classes rather than in SQL.
You must be very careful about time zones. Be explicit with time zones rather than relying on implicit default zones.
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, so your results may vary. Better to specify your desired/expected time zone 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 3-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" ) ;
LocalDate today = LocalDate.now( z ) ;
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.
Next, get the following Friday, or stick with today if it is already a Friday. Use a TemporalAdjuster to adjust between dates, specifically the one found in TemporalAdjusters.
LocalDate nextOrSameFriday = today.with( TemporalAdjusters.nextOrSame( DayOfWeek.FRIDAY ) ) ;
You said you were aiming at 10 AM.
LocalTime lt = LocalTime.of( 10 , 0 ) ; // 10 AM.
Combine with date and zone to get a specific moment.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust into UTC by extracting a Instant object. Same moment, same point on the timeline, but different wall-clock time.
Instant instant = zdt.toInstant() ;
Formulate your SQL to query your database column of type TIMESTAMP WITH TIME ZONE.
String sql = "SELECT * from tbl WHERE when_col = ? ; " ;
…
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
In this approach you have need for the dow or isodow functions in Postgres.
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.
You can use the Calendar constants minus 1 so you can match the PostgreSQL values ie: Calendar.SUNDAY = 1
I have written the following Java code to get a the first day of a week of year.
Calendar cal = Calendar.getInstance(Locale.GERMAN);
cal.clear();
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, Calendar.MONDAY);
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
DateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
System.out.println( sdf.format(cal.getTime()) );
By using the input week of year 53 it should result into an error acutally because this week of year does not exist in 2016. Instead it shows me the next possible first date from next year.
Is there a neat way to correct my code or do I have to check the input week of year by myself?
Thanks for your help.
tl;dr
If you mean a standard ISO 8601 week, use the YearWeek class from the ThreeTen-Extra library.
For specific week number in specific week-based year:
YearWeek.of( // Standard ISO 8601 week, where week # 1 has the first Thursday of the calendar year, and runs Monday-Sunday.
2018 , // Week-based year, NOT calendar year.
37 // Week-of-week-based-year. Runs 1-52 or 1-53.
)
.atDay( DayOfWeek.MONDAY ) // Returns a `LocalDate` object.
➡ Trap for java.time.DateTimeException if the input is not valid, if there is no such week in that week-based-year.
For current week:
YearWeek.now( // Standard ISO 8601 week, where week # 1 has the first Thursday of the calendar year, and runs Monday-Sunday.
ZoneId.of( "Pacific/Auckland" ) // Determining a week means determining a date, and that requires a time zone. For any given moment, the date varies around the globe by zone.
)
.atDay( DayOfWeek.MONDAY ) // Returns a `LocalDate` object.
Define “week”
Define what you mean by “week”. Is week # 1 the one with January 1st? Is week # 1 the first to have all seven days composed of days in the new year? If so, what is the first-last days of the week, Sunday-Saturday or Monday-Sunday or something else? Or is week # 1 the first to have a certain day of the week?
The troublesome old date-time classes defined a week by depending on Locale. If you fail to specify a Locale, the JVM’s current default Locale is silently implicitly applied. So your results can vary at runtime.
If possible I recommend using the standard ISO 8601 week definition. The week runs from Monday-Sunday, and week # 1 contains the first Thursday of the calendar year. So there are either 52 or 53 weeks per year.
Getting the current week means getting the current date. 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, so your results may vary. Better to specify your desired/expected time zone 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 3-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" ) ;
LocalDate today = LocalDate.now( z ) ;
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.
If you simply want a certain day-of-week on or before that date, then never mind about the week. Use a TemporalAdjuster implementation found in TemporalAjdusters. Specify your day-of-week via the DayOfWeek enum.
LocalDate mondayOnOrBeforeToday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;
ThreeTen-Extra library
If you do want to work with ISO 8601 weeks, there is limited support available in the IsoFields class. But I recommend instead that you add the ThreeTen-Extra library to your project. That library provides additional date-time classes that complement those built into Java SE 8 and later. In particular, you get the YearWeek class.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
YearWeek yw = YearWeek.now( z ) ;
Ask for the LocalDate of a day-of-week in that week.
LocalDate ld = yw.atDay( DayOfWeek.MONDAY ) ;
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.
I am trying to extract the day of month of today's date. I have this
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
JOptionPane.showMessageDialog(null, date.getDay());
but when the message dialog appears it show the number 5
and today it's the 8th. How can I set it to show what day of the month it is?
date.getDay() returns the day of the week. sunday is 0 and similarly saturday is 6.
Please see the java docs
As per the comment given below
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
String dayOfMonthStr = String.valueOf(dayOfMonth);
System.out.println(dayOfMonthStr);
Try this out.
JOptionPane.showMessageDialog(null, date.getTime());
You started to use the SimpleDateFormat class, but didn't do anything with it. Try:
System.out.println( new SimpleDateFormat("EEEE").format( new Date() ) );
System.out.println( new SimpleDateFormat("d").format( new Date() ) );
tl;dr
LocalDate.now() // Capture the current date as seen in the wall-clock time used by the people of a certain region, that region represented by the JVM’s current default time zone.
.getDayOfMonth() // Extract the day-of-month. Returns an `int`.
java.time
extract the day of month of today's date
The modern approach uses the java.time classes that supplant the troublesome old date-time classes bundled with the earliest versions of Java.
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.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone 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 3-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" ) ;
LocalDate today = LocalDate.now( z ) ;
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.
Interrogate the LocalDate for its day-of-month.
int dayOfMonth = today.getDayOfMonth() ;
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, with the team advising migration to the java.time classes. I am leaving this section intact as history.
In Joda-Time 2.3 in Java 7…
org.joda.time.DateTime theEighth = new org.joda.time.DateTime( 2013, 11, 8, 18, 0 ); // Default time zone.
System.out.println( "theEighth: " + theEighth );
System.out.println( "dayOfMonth of theEighth: " + theEighth.dayOfMonth().getAsText() );
When run…
theEighth: 2013-11-08T18:00:00.000-08:00
dayOfMonth of theEighth: 8
I just started going to university and basically just started using java and I want to know how to make a code that calculates the days between two dates but without the use of programs that take milliseconds and such things that I have seen in other answers.So this is the code I have created but it doesnt work perfectly it misses one day most of the times or something like that.Please I really need your help
Use a SimpleCalendar or GregorianCalendar classes...
but basing on what you posted, I'm unsure how to best suggest using those two... i'll draft a simple example shortly.
After some thought I'll just leave this here Difference in days between two dates in Java?
Taken from: http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm
An approach could be to calculate the number of days from a fixed time for both dates and then just subtract those days. This will give you the difference of days between date 1 and date 2
The following method returns the number of days passed since 0 January 0 CE
public int calculateDate( int day, int month, int year) {
if (month < 3) {
year--;
month = month + 12;
}
return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62);
}
In you code now you should calculate the number of days since 0BC for both dates and then subtract them:
public void run() {
....
int dayDifference = calculateDate(day1, month1, year1) - calculateDate(day2, month2, year2);
....
}
tl;dr
java.time.temporal.ChronoUnit.DAYS.between(
LocalDate.of( 2012 , Month.MARCH , 23 ) ,
LocalDate.of( 2012 , Month.MAY , 17 )
)
55
java.time
The modern approach uses java.time classes that supplant the troublesome old legacy date-time classes.
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.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone 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 3-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" ) ;
LocalDate today = LocalDate.now( z ) ;
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.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
ChronoUnit.DAYS
To get a count of days between two dates, call on the ChronoUnit enum object DAYS.
long days = ChronoUnit.DAYS.between( earlierLocalDate , laterLocalDate ) ;
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, 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, 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.