actually I'm a .NET guy and I wonder why such a simple and trivial things as handling date/time objects is that complicated
Everything I need is a object which holds the parameters for Day, Month, Year, Hour, Minute, Second...
and the possibility to manipulate theses values.
I don't want any conversion to any timezone.
Values of parameter should have the value is set!
Question 1:
How to create a date object from minutes?
Question 2:
How to create a date object from int's??
I've already spend hours to accomplish that and I can't believe that I really have to create my own DateTime implementation in Java!!
I tried it using Calendar(GMC, UTC...) and just Date but always the same.
The values got from my Date-TimePicker are transformed to daylight saving time or some other rule corresponding to the calender I defined.
One thing I really wonder about is that my time also get transformed when I use just "Date" object...
Cheers,
Stefan
I wonder why such a simple and trivial things as handling date/time objects is that complicated
The information technology industry as a whole went decades without tackling the surprisingly tricky problem of date-time handling.
Java originally inherited some code provided by Taligent/IBM. These became the java.util.Date,Calendar, GregorianCalendar, and related classes. They are terrible, bloody awful, flawed in design, and not object-oriented.
The Joda-Time project led by Stephen Colebourne was the first attempt I know of to tackle the date-time problem in a robust and competent manner. Later, Colebourne et al. took the lessons learned there to lead JSR 310, the java.time implementation, and related projects, the back-port in ThreeTen-Backport, and further additional functionality in ThreeTen-Extra.
So now Java has the industry-leading framework for date-time work in the java.time classes.
object which holds the parameters for Day, Month, Year, Hour, Minute, Second... and the possibility to manipulate theses values.
For a date-only, use LocalDate. For a date with time-of-day but lacking the context of a known offset-from-UTC or time zone, use LocalDateTime (not a moment). For a moment, a specific point on the timeline, use Instant (always in UTC), OffsetDateTime (a date with time-of-day in the context of a certain number of hours-minutes-seconds ahead/behind the prime meridian), or ZonedDateTime (a date and time with a time zone assigned).
Question 1: How to create a date object from minutes?
Not sure what you mean.
To represent a span-of-time unattached to the timeline, use Duration.
Duration d = Duration.ofMinutes( 10 ) ;
Instant now = Instant.now() ;
Instant tenMinutesFromNow = now.plus( d ) ;
If you have a count of minutes into the day, use LocalTime.MIN (00:00:00) with a Duration.
Duration d = Duration.ofMinutes( 10 ) ;
LocalTime lt = LocalTime.MIN.plus( d ) )
Question 2: How to create a date object from int's??
I am guessing you mean you want specify the year, month, day, and so on as a series of numbers. For that, use the LocalDateTime factory methad.
LocalDateTime ldt = LocalDateTime.of( 2020 , 1 , 23 , 15 , 30 , 0 , 0 ) ; // year, month, day, hour, minute, second, nanos fraction of second.
Or build up from a LocalDate and LocalTime.
LocalDate ld = LocalDate.of( 2020 , 1 , 23 ) ;
LocalTime lt = LocalTime.of( 15 , 30 ) ;
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
As mentioned above, a LocalDateTime cannot represent a moment. To determine a moment, specify a time zone. For example, in our code above, do you mean 3:30 PM in Tokyo, Toulouse, or Toledo — thee different moments, several hours apart.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust into UTC by extracting a Instant.
Instant instant = zdt.toInstant() ;
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.
Date and Calendar are not the best APIs in Java's library (to put it mildly, I consider them flaw-complementary), that's why a lot of Java programmers are using Joda-Time and many are looking forward to the inclusion in the standard distribution of JSR-310, a brandnew replacement for the old Date & Calendar mess. Joda has the added benefit that transitioning between Date and Joda's types is very easy (by using .toDate() or by using the relevant constructor that accepts a Date) so that using Joda's types inside your code and Date just at the "outer edges" where you interact with Date based code is not painful at all.
For your question 2, there's still a Date constructor that accepts int, and although it's deprecated you can still use it, see this thread. But I'd only suggest you take that route if switching to Joda isn't an option for you.
I suggest that you take a look at Joda Time, it's java dates designed right.
Related
Hi i am trying to get the current year in the below code however it is returning a 1970 year instead of 2020 last month this was working correctly but since we in January 2020, it is now returning a date from 1970, please assist
public String firstDateOfNextMonth(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar today = Calendar.getInstance();
Calendar next = Calendar.getInstance();
today.clear();
Date date;
next.clear();
next.set(Calendar.YEAR, today.get(Calendar.YEAR));
next.set(Calendar.MONTH, today.get(Calendar.MONTH)+ 1);
next.set(Calendar.DAY_OF_MONTH, 1);
date = next.getTime();
Log.d(TAG, "The Date: " + dateFormat.format(date));
return dateFormat.format(date);
}
If you have Java 8 or above, then you have java.time and you won't have to rely on outdated datetime implementations and you can do it this way:
public static String getFirstOfNextMonth() {
// get a reference to today
LocalDate today = LocalDate.now();
// having today,
LocalDate firstOfNextMonth = today
// add one to the month
.withMonth(today.getMonthValue() + 1)
// and take the first day of that month
.withDayOfMonth(1);
// then return it as formatted String
return firstOfNextMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
which prints the following when called today (2020-01-03) like System.out.println(getFirstOfNextMonth());:
2020-02-01
You might have to involve an external library, the ThreeTenAbp if you want it to work in Android below API level 26. Its use is explained in this question.
not sure why the today date gets cleared, remove today.clear() at line 4
today.clear(); initalize all elements of a date with the value 0
removing this line will give you the right answer
tl;dr
LocalDate // Represent a date-only value without a time-of-day and without a time zone.
.now( // Determine the current date as seen through the wall-clock time used by people in certain region (a time zone).
ZoneId.of( "America/Montreal" ) // Real time zone names have names in the format of `Continent/Region`. Never use 2-4 letter pseudo-zones such as `IST`, `PST`, or `CST`, which are neither standardized nor unique.
) // Return a `LocalDate`.
.with( // Move from one date another by passing a `TemporalAdjuster` implementation.
TemporalAdjusters // Class providing several implementations of `TemporalAdjuster`.
.firstDayOfNextMonth() // This adjuster finds the date of the first of next month, as its name suggests.
) // Returns another `LocalDate` object. The original `LocalDate` object is unaltered.
.toString() // Generate text in standard ISO 8601 format of YYYY-MM-DD.
See this code run live at IdeOne.com.
2020-02-01
Details
You are using terrible date-time classes that were made obsolete years ago by the unanimous adoption of JSR 310 defining the java.time classes.
The Answer by deHaar is correct. Here is an even shorter solution.
TemporalAdjuster
To move from one date to another, the java.time classes include the TemporalAdjuster interface. Pass one of these objects to the with method found on many of the other java.time classes.
TemporalAdjusters.firstDayOfNextMonth()
Several implementations of that interface are found in the class TemporalAdjusters (note the s plural). One of those is firstDayOfNextMonth(), just what you need.
Get today's date. A time zone is required, as for any given moment the date varies around the globe by time zone. If omitted, your JVM's current default time zone is implicitly applied. Better to be explicit.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;
Get your TemporalAdjuster object.
TemporalAdjuster ta = TemporalAdjusters.firstDayOfNextMonth() ;
Apply that adjuster to get another LocalDate object. Note that java.time classes are immutable by design. So we get a new object rather than altering the original.
LocalDate firstOfNextMonth = today.with( ta ) ;
We can shorten this code to a one-liner, if desired.
LocalDate firstOfNextMonth =
LocalDate
.now(
ZoneId.of( "Africa/Tunis" )
)
.with(
TemporalAdjusters.firstDayOfNextMonth()
)
;
Text
Your desired output format of YYYY-MM-DD complies with the ISO 8601 standard used by default in the java.time classes when parsing/generating text. So no formatting pattern need be specified.
String output = firstOfNextMonth.toString() ;
2020-02-01
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.
You are using Calendar.clear() which clears all the fields of your calendar, and essentially reverts it to 1/1/1970 (epoch time 0).
remove today.clear() and you'll get the correct answer
see more here
Remove next.clear();. As Calendar next= Calendar.getInstance(); initiates next with the current date, in your cases Fri Jan 03 2020 15:07:53. And when you do next.clear(), it sets to the inital epoch.
Epoch, also known as Unix timestamps, is the number of seconds (not
milliseconds!) that have elapsed since January 1, 1970 at 00:00:00 GMT
(1970-01-01 00:00:00 GMT).
This question already has answers here:
How to find the duration of difference between two dates in java?
(18 answers)
Closed 4 years ago.
i wanted to take an input of date and time in the below format and need to calculate the time difference between two, can anyone suggest how to take below string as input and calculate the time difference.
user defined datetime input in java
String startTime= "11/27/2018+09:00:00";
String endTime= "11/28/2018+13:00:00";
The + is a separator (not a sign as in plus or minus).
Senseless input
String startTime= "11/27/2018+09:00";
String endTime= "11/28/2018+13:00";
These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.
For an offset to have meaning, you need a date and a time-of-day.
We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.
The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.
The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.
Guesswork
If correcting the source of this data is not feasible, then we can plod on with guesswork.
Extract the date, separate from offset.
String input = "11/27/2018+09:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );
localDate.toString(): 2018-11-27
zoneOffset.toString(): +09:00
OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );
2018-11-27T00:00+09:00
We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.
Duration d = Duration.between( odt , odtLater ) ;
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.
In java 8 there is:
LocalDateTime: use this if you need to deal with date and time.
LocalDate: use this if you need to deal with date only.
ZonedDateTime: use this if you need to deal with date time with time zone.
OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)
Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).
However, I think you can solved it like this:
Create a method that convert your date string into OffsetDateTime like this:
private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
{
//TODO: assert that dateWithTimeOffset is valid
String date = dateWithTimeOffset.substring (0, 10);
String timeOffset = dateWithTimeOffset.substring (10, 13);
//define your date pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");
return LocalDate.parse (date, formatter) // create LocalDate
.atStartOfDay () // convert it to LocalDateTime with time 00:00:00
.atOffset (ZoneOffset.of(timeOffset)); // apply the offset
}
Then you can simple create your OffsetDateTime like this:
OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");
OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");
You can create duration using OffsetDateTime like this:
Duration duration = Duration.between (startTime, endTime);
Duration have everything you need related with time duration, for example:
duration.toHours () // will give you the hour duration
I want to retain CST time always with offset -6, at present I am getting as 2018-03-15T05:08:53-05:00.
But I want to change it as with offset -6 like 2018-03-15T05:08:53-06:00 through out the year.
TimeZone tz= TimeZone.getdefault();
if(tz.inDayLightTime())
{
getCSTDate(cal)
// I would like to change the logic here.
}
public XMLGregorianCalendar getCSTDate(Calendar cal)
{
return XMLGregorianCalendar;
}
my input type : calendar
output : XMLGregorianCalendar
Then don't use a timezone that tracks Daylight Saving Time changes (which is probably the case of yours TimeZone.getDefault()).
If you want a fixed offset, you can do:
TimeZone tz = TimeZone.getTimeZone("GMT-06:00");
Not sure why you want that, because if you're dealing with timezones, you must consider DST effects. And 2018-03-15T05:08:53-06:00 is not the same instant as 2018-03-15T05:08:53-05:00, so changing the offset while keeping all the other fields is usually wrong - as it's not clear why you want that and what you want to achieve, I can't give you more advice on that.
tl;dr
If you want the current moment as seen through a fixed offset-from-UTC, use OffsetDateTime with ZoneOffset.
OffsetDateTime.now(
ZoneOffset.ofHours( -6 )
)
Details
always with offset -6
The Answer by watssu is correct: If you don’t want the effects of Daylight Saving Time (DST), don’t use a time zone that respects DST.
If you always want an offset-from-UTC fixed at six hours behind UTC, use an OffsetDateTime.
ZoneOffset offset = ZoneOffset.ofHours( -6 ) ;
OffsetDateTime odt = OffsetDateTime.now( offset ) ; // Ignores DST, offset is fixed and unchanging.
Be clear that an offset is simply a number hours, minutes, and seconds displacement from UTC. In contrast, a time zone is a history of past, present, and future changes in offset used by the people of a particular region. So generally, you should be using a time zone rather than a mere offset. Your insistence on a fixed offset is likely unwise.
The 3-4 letter abbreviations such as CST are not time zones. They are used by mainstream media to give a rough idea about time zone and indicate if DST is in effect. But they are notstandardized. They are not even unique! For example, CST means Central Standard Time as well as China Standard Time or Cuba Standard Time.
Use real time zones with names in the format of continent/region.
Avoid all the legacy date-time classes such as TimeZone now supplanted by the java.time classes. Specifically, ZoneId.
ZoneId z = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Respects DST changes in offset.
If your real issue is wanting to detect DST to alter your logic, I suggest you rethink the problem. I suspect you are attacking the wrong issue. But if you insist, you can ask for the offset currently in effect on your ZonedDateTime, and you can ask a ZoneId if DST is in effect for any particular moment via the ZoneRules class.
ZoneOffset offsetInEffect = zdt.getOffset() ;
And…
Boolean isDstInEffect = zdt.getZone.getRules().isDaylightSavings( zdt.toInstant() ) ;
On that last line, note the incorrect use of plural with s on isDaylightSavings.
The XMLGregorianCalendar class is part of the troublesome old legacy date-time classes, now supplanted by the java.time classes, specifically ZonedDateTime. To inter-operate with old code not yet updated to java.time, convert to the modern class via the legacy class GregorianCalendar.
ZonedDateTime zdt = myXmlCal.toGregorianCalendar().toZonedDateTime() ;
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.
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.