Specify a date-time range with `Calendar` in Android - java

StackOverflow community,
I' currently working on my new project and I'm new to Java and Android Studio.
I have written my own Entry class with two Calendar variables.
Is there a shorter and cleaner way to create a new Entry object like in the following code?
//MainActivity.java
//....
private ArrayList<Entry> initEntrys() {
ArrayList<Entry> list = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
Calendar mStartDate = calendar;
Calendar mEndDate = calendar;
mStartDate.set(2019, 12, 20, 7, 0);
mEndDate.set(2019, 12, 20, 10, 0);
list.add(new Entry(mStartDate, mEndDate));
return list;
}
Any help would be really appreciated. :)

tl;dr
Never use the legacy date-time classes such as Calendar. Use only java.time classes.
For a date with time-of-day but lacking a time zone or offset-from-UTC, use java.time.LocalDateTime class.
LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 ) // year, month, day , hour , minute.
Avoid legacy date-time classes
Never use Calendar. That class is terrible, flawed in its design. It was supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
In contrast to the legacy classes, the java.time classes are immutable by design and therefore thread-safe.
Rather than use constructors with new, we instantiate java.time objects by calling static factory methods such as LocalDateTime.of.
Not a moment
If you are consciously working without the context of a time zone or offset-from-UTC, use LocalDateTime objects.
LocalDateTime start = LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 ) ; // Passing year, month, day , hour , minute. The second and fractional-second both default to zero.
LocalDateTime stop = LocalDateTime.of( 2019 , 12 , 20 , 10 , 0 ) ;
Moment
If you are trying to represent moments, specific points on the timeline, then LocalDateTime is the wrong class.
For tracking moments, you need the context of a time zone (or less preferably, an offset-from-UTC). For that, use ZonedDateTime as seen in the Answer by CrackerGen.
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….

I will try to complete Answer by Basil Bourque by covering a time zoned date using the ZonedDateTime class.
I have used UTC time zone in the example but you can customize with the suitable time zone you need.
LocalDateTime ldtStart = LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 , 0 , 0 ) ;
ZonedDateTime ldtZonedStart = ldtStart.atZone(ZoneId.systemDefault());
ZonedDateTime utcZonedStart = ldtZonedStart.withZoneSameInstant(ZoneOffset.UTC);
LocalDateTime ldtStop = LocalDateTime.of( 2019 , 12 , 20 , 10 , 0 , 0 , 0 ) ;
ZonedDateTime ldtStopZoned = ldtStop.atZone(ZoneId.systemDefault());
ZonedDateTime utcZonedStop = ldtStopZoned.withZoneSameInstant(ZoneOffset.UTC);

Related

Change the time based on the gmt area on Android

I'm a beginner in android development and I've been searching for hours to find an answer for my question but I didn't really understand anything I found.
The match between 2 teams is starting at 20:00 gmt and I want to make it + - based on the area. For example in germany +1 gmt the time should be 21:00. I only want the hours and minutes format like that.
tl;dr
OffsetDateTime
.of(
LocalDate.of( 2021 , Month.MARCH , 23 ) ,
LocalTime.of( 20 , 0 ) ,
ZoneOffset.UTC
) // Returns a `OffsetDateTime` object.
.atZoneSameInstant(
ZoneId.of( "Europe/Berlin" )
) // Returns a `ZonedDateTime` object.
.toLocalTime() // Returns a `LocalTime` object.
.toString() // Returns a `String` object, with text in standard ISO 8601 format.
21:00
Details
Location does not necessarily correlate to time zone. Users choose their time zone as a preference. Servers should generally be set to UTC (an offset of zero). You can get the JVM’s current default time zone by calling ZoneId.systemDefault. If crucial, you should explicitly ask the user to confirm their desired zone.
I only want the hours and minutes format like that.
Date-time objects are not text, and do not have a "format". Think in terms of the logic needed for handling date-time values rather than in terms of manipulating strings.
starting at 20:00 gmt and I want to make it + - based on the area
Representing that 8 PM in UTC (the new GMT):
LocalDate tomorrow = LocalDate.now( ZoneOffset.UTC ).plusDays( 1 ) ;
LocalTime eightPM = LocalTime.of( 20 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( tomorrow , eightPM , ZoneOffset.UTC ) ;
For example in germany +1 gmt the time should be 21:00
Define your desired time zone.
ZoneId z = ZoneId.of( "Europe/Berlin" ) ;
Adjust from the OffsetDateTime to a ZonedDateTime.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
See that code run live at IdeOne.com.
odt.toString(): 2021-02-17T20:00Z
zdt.toString(): 2021-02-17T21:00+01:00[Europe/Berlin]
The odt & zdt objects seen here both refer to the very same simultaneous moment, the same point on the timeline.
This has all been covered many times before on Stack Overflow. Search to learn more.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
It's not Android specific but just a general question about Java.
Use Calendar and SimpleDateFormat like this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.set(2021, 1, 16, 20, 00, 00); // 2021-02-16T20:00:00 GMT
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
System.out.println(simpleDateFormat.format(calendar.getTime()));
Set (input) your date as GMT. Then format it GMT+01:00 with SimpleDateFormat and print (output) it.

android Date + 14 and custom days

I have 4 Textview's (named date0, date1, date2 and date3) and 1 editText (name datex), I need code that will show me today date in date0 (dd,mmm,yyyy) , tomorrow in date1, today + 14days in date2.
For date3 I need code to put custom date from editext (named- datex), when click on datex, enter value 1,2 or any number(10 for example), and then show date in date3=today+10.
Thanks
(I could not get it from tutorials..., I have errors)
I do not have code.
It do not need to be saved, only to show dates. UTC date would be better if it is possible.
Today
Get the current date.
Specify a time zone (ZoneId) : for any given moment, the date varies around the globe by zone.
LocalDate today = LocalDate.now( ZoneOffset.UTC ) ;
Either specify custom formatting pattern (search Stack Overflow to learn more), or better, let java.time automatically localize. Specify a locale to determine the human language and cultural norms used for localization.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale ) ;
String outputToday = today.format( f ) ;
Tomorrow
Add a day to get tomorrow.
LocalDate tomorrow = today.plusDays( 1 ) ;
Generate text in the same manner as seen above.
String outputTomorrow = tomorrow.format( f ) ;
In two weeks
And add two weeks for future date.
LocalDate twoWeeksAhead = today.plusWeeks( 2 ) ;
Generate string as seen above.
All of this has been covered many many times already on Stack Overflow. So search to learn more.
See the code above run live at IdeOne.com.
outputToday: 7 nov. 2019
outputTomorrow: 8 nov. 2019
outputTwoWeeks: 21 nov. 2019
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….

Java Calendar getTimeInMillis returning wrong time

I am working with the Java Calendar class for android however I am getting some unexpected behaviour.
When I test the following code it gives me the desired results:
Calendar cal = Calendar.getInstance();
cal.getTimeInMillis() - System.currentTimeMillis(); // returns 0 indicating that they are synced
However when I change the values of the Calendar instance, it seems that it no longer returns the correct value for getTimeMillis.
For example:
// Current time : 1:56pm
cal.set(Calendar.HOUR, 13);
cal.set(Calendar.MINUTE, 0);
cal.getTimeInMillis(); // returns 1411448454463
System.currentTimeMillis(); // returns 1411407834463
cal.getTimeInMillis() - System.currentTimeMillis(); // returns 40620000
As you can see cal.getTimeInMillis() returns a number larger than System.currentTimeMillis() even though the time should be earlier (1:00pm vs 1:56pm).
Any help would be greatly appreciated!
tl;dr
ZonedDateTime.now( // Capture the current moment…
ZoneId.of( "Africa/Tunis" ) // … as seen through the wall-clock time used by the people of a certain region (time zone).
) // Returns a `ZonedDateTime` object.
.with( // Adjusting…
LocalTime.of( 13 , 0 ) // …by replacing the time-of-day
) // Produces a fresh (second) `ZonedDateTime` object, with values based on the original. Known as Immutable Objects pattern.
.toString()
2018-04-24T13:00+01:00[Africa/Tunis]
java.time
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes originally bundled with the earliest versions of Java.
Get the current moment as seen through the wall-clock time used by the people of a certain region (a time zone).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
To represent the new desired time-of-day, use LocalTime.
LocalTime lt = LocalTime.of( 13 , 0 ) ; // 1 PM.
Adjust the existing ZonedDateTime to this time-of-day, producing a fresh ZonedDateTime object.
ZonedDateTime zdtThirteen = zdt.with( lt ) ;
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….

java.util.Date to java.sql.Date conversion gives wrong month

Consider the following snippet:
Calendar futureDate = Calendar.getInstance();
int year = 2011;
int month = 11;
int day = 14;
futureDate.set(year,month, day);
System.out.println(futureDate.toString());
java.sql.Date sqlDate = new java.sql.Date( futureDate.getTime().getTime());
The printout from futureDate.toString() is:
.....YEAR=2011,MONTH=11,WEEK_OF_YEAR=43,WEEK_OF_MONTH=4,DAY_OF_MONTH=14,DAY_OF_YEAR=289,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=32,SECOND=51,MILLISECOND=117,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
which shows that the Calendare object holds the correct date. However, after converting to sql date and storing in the database (MySQL through JDBC), the MySQL table shows '2011-12-14' for this date instead of '2011-11-14'.
I would have suspected locale and time zone, but these would cause discrepancy in the time of day not in the month part of the date.
Any clues to what I did wrong?
Calendar#set(int, int, int) interprets the month argument as zero-based, so futureDate.set(2011, 11, 14) sets the calendar's month to December.
tl;dr
LocalDate.of( 2011 , 11 , 14 ) // November 14th, 2011
Details
The Answer by Matt Ball is correct. But now there is a much improved way.
java.time
The troublesome old date-time classes such as Calendar, java.util.Date, and java.sql.Date are now legacy, supplanted by the java.time classes.
Unlike the legacy classes, the java.time classes have sane numbering, such as months being numbered 1-12 for January to December, and 1-7 for Monday to Sunday.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2011 , 11 , 14 ) ;
Or use the handy Month enum.
LocalDate ld = LocalDate.of( 2011 , Month.NOVEMBER , 14 ) ;
With a JDBC driver supporting JDBC 4.2 and later, you may pass your java.time objects directly to the database.
myPreparedStatement.setObject( … , ld ) ;
When fetching, use getObject.
LocalDate ld = myResultSet.getObject( … , LocalDate.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.
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.

Ask Gregorian Calendar for hour of day in java

I'm using a Gregorian Calendar to set a specific date and time to an application using the set function of the Gregorian Calendar. When i use the getTime() method, it gives me the right output however when i try to access the Hour_Of_Day and Minute it gives a wrong number.
Calendar time = new GregorianCalendar();
time.set(2010, Calendar.JANUARY, 1, 7, 20,0);
hour = time.HOUR_OF_DAY;
minute = time.MINUTE;
The hour gives an output of 11 and the minute gives an a value of 12.
Any suggestions on how to fix this?
Thanks
Your code is just assigning hour/minute to constants. You need to call Calendar.get(int):
hour = time.get(Calendar.HOUR_OF_DAY);
minute = time.get(Calendar.MINUTE);
tl;dr
myGregCal
.toZonedDateTime() // Convert from legacy class GregorianCalendar to modern ZonedDateTime.
.getHour() // Get hour-of-day, 0-23.
java.time
Much easier with the modern java.time classes that replace those troublesome old legacy date-time classes.
The ZonedDateTime class represents a moment on the timeline in a specific time zone with a resolution of nanoseconds.
Convert from your GregorianCalendar using new methods added to the old classes.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
Or start fresh without the GregorianCalendar class.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( 2010 , Month.JANUARY , 1 , 7 , 20 , 0 , 0 , z );
If you want to work with just the time-of-day portion, extract a LocalTime.
LocalTime localTime = zdt.toLocalTime() ;
If you really want the integer numbers of hours and minutes, you can interrogate for those.
int hour = zdt.getHour();
int minute = zdt.getMinute();
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.

Categories