I've to write a generic code as such, it should give months difference between two dates.
For eg., my input data will be
1. date1 = 22/01/2016
date2 = 30/03/2016
2. date1 = 22/01/2016
date2 = 20/12/2015
based on months difference, I've to move forward(if date2 is future date to date1) or backward(if date2 is past date to date1), those many times.
You could simply compare these two dates as stated here
According to the result you just have to call the same code as if you have clicked on the button yourself (just call the respective mehtod (if you don't use a method for that I would advise you to do so))
Greetings Raven
EDIT:
The difference betweent two dates can be calculated like this
Calendar data = Calendar.getInstance();
Calendar data2 = Calendar.getInstance();
int diff =(int) Math.round(( (data2.getTimeInMillis() - data.getTimeInMillis()) /* ms*/
/ 1000.0 /* seconds*/
/ 3600.0 /*hours*/
/ 24.0 /*days*/
/ 30.0 ))/* monts*/;
With Math.round you ensure months of 31 and 28 days return the right value
Replace data and data2 for your own values
tl;dr
Period.between(
LocalDate.of( 2016 , Month.JANUARY , 22 ) ,
LocalDate.of( 2016 , Month.MARCH , 30 )
).isNegative()
Details
Your Question is not clear, but this might help point you in the right direction.
Avoid the troublesome old date-time classes such as Date that are now legacy, supplanted by the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
date1 = 22/01/2016
date2 = 30/03/2016
LocalDate start = LocalDate.of( 2016 , Month.JANUARY , 22 ) ;
LocalDate stop = LocalDate.of( 2016 , Month.MARCH , 30 ) ;
Period
Calculate the number of days, months, and years elapsed as a Period.
Period period = Period.between( start , stop ) ;
Test if the stop comes before the start, meaning the elapsed time is negative, going backwards along the timeline.
Boolean isTimeGoingBackwards = period.isNegative() ;
Months
Your comments mention getting a number of months. Understand multiple ways to count months:
Count days elapsed, divided by 30 as the length of a generic month.
Count of calendar months completely covered
Count of calendar months touched by the span of time
Java offers at least some of these. Read the documentation to decide which meets your needs. If going backwards in time, the resulting number is negative.
ChronoUnit.MONTHS
long months = ChronoUnit.MONTHS.between( start , stop ) ;
Period.toTotalMonths
int months = Period.between( start , stop ).toTotalMonths() ;
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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
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
Hello I'm trying to convert a string in the format "17:50" to a date in android but when I try to run this code I get the correct hour from the string but the full date is from 1970. I need this date to schedule some local notifications on a given time of the day or in the next day.
String dtStart = "17:50";
SimpleDateFormat format = new SimpleDateFormat("H:mm");
try {
Calendar cal = Calendar.getInstance();
Date date = format.parse(dtStart);
cal.setTime(date);
System.out.println(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
Thu Jan 01 17:50:00 BRT 1970
It's not an error, your code works well. Just if you want to get current date, you have to add the difference between current day and 1st of January 1970.
Your parsed date gives you 17:30 hours, which means 17 * 60 * 60 * 1000 ms + 30 * 60 + 1000 ms.
This way you can find current day: https://stackoverflow.com/a/1908419/4142087
What Anton suggested was correct, and the current day / next day logic is your custom implementation. You have to check current time and if it past that time, jump to setting up the alarm the next day.
java.time
You need a time-of-day class to represent your intended meaning. The legacy date-time classes from the earliest versions of Java lack such a class. The java.sql.Time class pretends to do this, but actually contains a date as well due to poor design decisions.
LocalTime
You want the LocalTime class for a time-of-day value without a date and without a time zone.
It uses a generic 24-hour single-day clock. Adding/subtracting spans of time wraps around the clock since it lacks any concept of dates.
Define a formatting pattern to match your input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "H:mm" ) ; // Uppercase `H` means 24-hour clock, lowercase `h` means 12-hour clock.
Parse input string.
String input = "7:50" ;
LocalTime lt = LocalTime.parse( input , f ) ;
Generate a string in standard ISO 8601 format.
String output = lt.toString() ;
07:50
Perhaps your business logic requires assigning the time-of-day to a date. To determine a moment, a point on the timeline, you must also specify a time zone.
LocalDate ld = LocalDate.of( 2018 , Month.MARCH , 27 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
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.
Hy guys!
I'm writing a software to keep track of room bookings. Each room has a day of booking, a start time, an end time. The problem is I may have a booking in between two day (eg. from 18-02-2015 23:00 to 19-02-2015).
How can I automate this increasing process without asking the user to insert an end date?
I'm using Calendar for the date but for hours and minutes I just take values from two TextFields.
You could specify the amout of days a room is booked. Then you just have to add the number of days to your first Calendar object.
Working example how to add days in a simple way:
int days = 2; //default duration, placeholder
Calendar now = Calendar.getInstance();
Calendar end = (Calendar) now.clone();
end.add(Calendar.DATE, days);
The Calendar end would then be set the current time in two days.
Normally I wouldn't recommend using Object.clone(), but this answer says it is safe to do so.
There is no way to project a time span with the old Calendar-API (with just one Calendar). But if you could use the new Java 8 Date and Time API, you may use Periods und Durations. They may come in useful, if you need to determine durations for bookings.
However, I can just recommend you to look into the API, since I haven't worked with it enough to provide a useful example.
tl;dr
ZonedDateTime.of( 2015 , Month.FEBRUARY , 18 , 23 , 0 , 0 , 0 , ZoneId.of( "Europe/Paris" ) )
.plus( Duration.ofHours( 3 ) )
2015-02-19T02:00:00+01:00[Europe/Paris]
java.time
The accepted answer uses the outmoded old legacy date-time classes that have proven to be so troublesome and confusing. Now supplanted by the java.time classes.
To specify a moment on the timeline, include the time zone to give context to your date-and-time.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime start = ZonedDateTime.of( 2015 , Month.FEBRUARY , 18 , 23 , 0 , 0 , 0 , z );
Track your reserved number of hours as a Duration.
Duration duration = Duration.ofHours( 3 );
The ZonedDateTime class knows how to do math with a Duration.
ZonedDateTime zdtStop = zdtStart.plus( duration );
You say you have two data-entry fields for hours and minutes. Convert each text entry to a number. The Long class parses a string to a long primitive.
From those numbers get a Duration of hours and minutes.
Duration duration = Duration.ofHours( Long.parseLong( hoursEntry ) )
.plusMinutes( Long.parseLong( minutesEntry ) ) ;
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 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 get day ,month and year from a Julian date.
String date = "13136";//Julian date
Date convertedDate = new SimpleDateFormat("yyDDD").parse(date);
System.out.println(convertedDate);
It prints
Thu May 16 00:00:00 BST 2013
which is correct.
Now I want to get Day , Month and Year from it
Calendar cal = Calendar.getInstance();
cal.setTime(convertedDate);
System.out.println(cal.get(Calendar.MONTH));
It prints 4 .
It should print 5 instead of 4 . Why is it not printing as correct ? What I have done wrong here?
As per the javadoc of Calendar.MONTH:
Field number for get and set indicating the month. This is a
calendar-specific value. The first month of the year in the Gregorian
and Julian calendars is JANUARY which is 0; the last depends on the
number of months in a year.
So months starts from zero so your output 4 is correct, for general usecase in your code it would be safe to add 1 to it unless you use this values as MONTH value in Calendar again.
As the javadocs state, months begin at zero: 0 = January, 1 = February, and so on.
tl;dr
LocalDate.parse (
"13136",
DateTimeFormatter.ofPattern ( "uuDDD" )
).getMonthValue()
5
…for month of May 2013.
Ordinal, not Julian
Your use of the word “Julian” is technically incorrect, though common. Folks seem to confuse day-of-year (1-365 or 1-366) with practice of counting the number of days elapsed since January 1, 4713 BC used in some scientific fields.
The terms “ordinal date” or day-of-year are more clear.
ISO 8601
Your format for ordinal dates is not standard. Whenever possible, use the standard ISO 8601 formats:
YYYY-DDD
YYYYDDD
java.time
The modern way is with the java.time classes that supplant the troublesome old legacy date-time classes.
DateTimeFormatter
Note that the formatting pattern codes in DateTimeFormatter class are similar to the legacy class but not exactly the some.
String input = "13136"; //Julian date
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuDDD" );
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate localDate = LocalDate.parse ( input, f );
Dump to console.
System.out.println ("localDate: " + localDate );
localDate: 2013-05-16
Month
You can ask about the month of that LocalDate. The Month enum pre-defines a dozen objects, one for each month of the year. And unlike the crazy legacy classes, these are sanely numbered 1-12 for January-December.
If you are passing the month number around your code, I suggest you instead pass around these enum objects. Doing so gives you type-safety, valid values, and self-documenting code.
Month month = localDate.getMonth();
You can get the localized name of that month if needed.
String output = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ); // Or Locale.US, Locale.ITALY, whatever.
If you truly do need the number of the month 1-12, ask in either way.
int monthNumber = month.getValue() ;
int monthNumber = localDate.getMonthValue() ;
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 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 have tried the example given in stack overflow
how to get a list of dates between two dates in java
The code works perfectly. But there is a small problem. I don't get the end date also in my List. How do I choose to include/exclude the start date and include the end date ?
Do, I do that manually by using remove() and add() or can Joda API do that for me?
Based on API, it seems there is no direct way to choose include.
One hack may be, just add +1 to number of days.
List<LocalDate> dates = new ArrayList<LocalDate>();
int days = Days.daysBetween(startDate, endDate).getDays()+1;
for (int i=0; i < days; i++) {
LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
dates.add(d);
}
Using java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Half-open
Date-time work commonly uses the Half-Open approach to defining a span of time where the beginning is inclusive and the ending is exclusive. I believe consistent use of this approach in both your code and in your users’ business makes life much easier, avoiding amibiguities that can result in misunderstandings or errors.
The java.time classes use the Half-Open approach. Keep that in mind when using Period, Duration, and ChronUnit classes.
LocalDate start = LocalDate.of( 2017 , 1 , 23 );
LocalDate stop = LocalDate.of( 2017 , 2 , 14 );
List<LocalDate> dates = new ArrayList<>( (int) ChronoUnit.DAYS.between( start , stop ) ) ;
LocalDate ld = start ;
while( ld.isBefore( stop ) ) { // Half-open approach, ending is exclusive.
dates.add( ld );
// Set up the next loop.
ld = ld.plusDays( 1 );
}
If you insist on that ending date to be inclusive, add a day to the input.
LocalDate stop = LocalDate.of( 2017 , 2 , 14 ).plusDays( 1 ); // Effectively making ending date inclusive.
…or (A) change the logic of the while test from isBefore to ! isAfter, and (B) add one to the initial capacity of the ArrayList.
List<LocalDate> dates = new ArrayList<>( ( (int) ChronoUnit.DAYS.between( start , stop ) ) + 1 ) ; // Add one to accommodate inclusive ending (*not* Half-Open).
LocalDate ld = start ;
while( ! ld.isAfter( stop ) ) { // Ending is inclusive (*not* Half-Open). So using "not after" logic rather than "is before".
dates.add( ld );
// Set up the next loop.
ld = ld.plusDays( 1 );
}
Stream<LocalDate>
By the way, this code gets simpler in Java 9 where you can get a Stream<LocalDate from LocalDate::datesUntil method. That call returns a sequential ordered stream of dates.
A variant of that method lets you specify an amount to increment the dates. So, for example, instead of the default of single day increment, you can increment by two to get every-other-day.
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 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.