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.
Related
In my application i want get some data from server and i should cast date and time!
I receive date and time with this format end_date: "2020-04-08 13:11:14" from server.
I want get now date and time from my device and to calculate with above date (end_date), if this time under 24h i should show for example 15 hour later, but if this time more than 24h i should show 2 days later!
But i don't know how can i it?
Can you help me with send code or send to me other tutorials?!
I searched that but I didn't find anything.
java.time
The modern approach uses java.time classes.
Parse the input string as a LocalDateTime.
To parse, replace the SPACE in the middle with a T to comply with ISO 8601 standard.
String input = "2020-04-08 13:11:14".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Your input lacks an indicator of any time zone or offset-from-UTC. So we do not know if this was meant to be 1 PM in Tokyo Japan, 1 PM in Toulouse France, or 1 PM in Toledo Ohio US. So you cannot reliably compare this to the current date and time.
If you want to presume this string was meant to tell time in your time zone, then assign a time zone to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime then = ldt.atZone( z ) ;
Capture the current moment in the same zone.
ZonedDateTime now = ZonedDateTime.now( z ) ;
Calculate 24 hours later.
ZonedDateTime twentyFourHoursFuture = now.plusHours( 24 ) ;
Compare.
boolean within24Hours = then.isBefore( twentyFourHoursFuture ) ;
Determine elapsed time using the Duration class.
Duration duration = Duration.between( then , now ) ;
If you want to trust the JVM’s current default time zone, call ZoneId.systemDefault. Beware that this default can be changed by other Java code during execution of your app.
ZoneId z = ZoneId.systemDefault() ;
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.
Try using the datetime library, or you can see this answer.
Also if you can choose, it's a good habit to pass the times in UTC from/to the server, it'll save some localization and timezone troubles.
i have a Date field expiryDate with value Thu Nov 21 00:00:00 IST 2019 But i am trying to get the endDate time to the before to the day by removing a millisecond from the time as Thu Nov 20 23:59:59 IST 2019
do we have any methods to remove a millisecond from the given Date.
java.time
Avoid the terrible date-time classes that are now legacy as of JSR 310. Now supplanted by the modern java.time classes.
You can easily convert back and forth. Call new conversion methods addd to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
And back again.
java.util.Date myJavaUtilDate = Date.from( instant ) ;
Subtract a millisecond.
Instant oneMilliEarlier = instant.minusMillis( 1 ) ;
Half-Open
But I suggest you not take this approach. Do not track a span of time by its last moment.
Your attempt to track the last moment of the day is problematic. You are losing that last millisecond of time. Doing so leaves a gap until the first moment of the next day. And when switching to a finer time slicing such as microseconds used by some systems such as databases like Postgres, and the nanoseconds used by other software such as the java.time classes, you have a worse problem.
A better approach is the Half-Open approach commonly used in date-time handling. The beginning of a span-of-time is inclusive while the ending is exclusive.
So an entire day starts at the first moment of the day, typically at 00:00:00 (but not always!), and runs up to, but does not include, the first moment of the next day.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
ZonedDateTime start = zdt.toLocalDate().atStartOfDay( z ) ;
ZonedDateTime stop = start.plusDays( 1 ) ;
Tip: For working with such spans of time, add the ThreeTen-Extra library to access the Interval class.
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.
yes. i just tried with the above mehtod getTime() returns milliseconds to the given date.
and substracting a millisecond is giving me a correct output.
new Date(milliseconds) giving me the Date format.
Thanks #Elliott Frisch
I want to get the current time in milliseconds. I'm using System.currentTimeMillis() but this returns the date as well as the time. I simply want "15:03" in milliseconds, not the date too.
Note that I want an integer and not a formatted string. If it was 08:30, this is the equivalent to 30600 seconds, which is in turn equivalent to 30600000 milliseconds. This is the value I want
tl;dr
Duration.between( todayStart , now ).toMillis()
Details
Get the current moment in the wall-clock time used by the people of a certain region (a time zone).
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
Get the first moment of the day. Do not assume this is 00:00:00. Let java.time determine.
ZonedDateTime todayStart = now.toLocalDate().atStartOfDay( z ) ;
Represent the delta between them, the span of time unattached to the timeline, as a Duration.
Duration d = Duration.between( todayStart , now ) ;
A Duration has a resolution of nanoseconds. That is finer than the milliseconds you desire. A convenience method will ignore any microseconds or nanoseconds for you.
long millisSinceStartOfToday = d.toMillis() ;
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.
Use the LocalTime class:
long millis = LocalTime.now().toNanoOfDay() / 1_000_000;
Basil Bourque correctly points out that it isn’t always this simple: a Daylight Saving Time change (such as will occur in most of the US this Sunday) can mean that, for example, there may not be eight hours between midnight and 8 AM.
You can account for this by using a ZonedDateTime, which accounts for all calendar information, including DST changeovers:
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime start = now.truncatedTo(ChronoUnit.DAYS);
long millis = ChronoUnit.MILLIS.between(start, now);
Since you are interested in the millis since midnight in the GMT timezone, the easiest approach is probably:
int millis = LocalTime.now(ZoneOffset.UTC).get(ChronoField.MILLI_OF_DAY);
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.
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.