Date wrong increasing in Java for Android - java

I am trying to build a calendar app in Android Studio. Everything works fine despite one little thing. When I have a repeating event (lets say weekly), and after inserting it - which works fine - and I tried to increase it with the function:
calendar.add(Calendar.DAY_OF_YEAR, 7);
The following happens:
It inserts events exactly to the end of the month and in the next year in the same month again, so how can I achieve, that also the month increases and the event will appear next month?
Hope I could explain what I mean.

If you want to add a week (7 days) in your calendar, you should use Calendar.DATE and not Calendar.DAY_OF_YEAR:
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, 7);

Joda-Time
Alternatively you could use the Joda-Time library. The old java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.
If you want only date without time-of-day, use the LocalDate class.
LocalDate today = LocalDate.now(); // Gets today's date using JVM’s current default time zone. You may want to specify a time zone instead, passing a `DateTimeZone` object.
LocalDate weekLater = today.plusWeeks( 1 );
java.time
Java 8 and later comes bundled with the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. Intended to be the successor to Joda-Time. See the Tutorial.
Java 8 technology is not currently available in Android. But there have been some back-port projects. I've heard the back-port may work well in Android but I do not know details.

Related

Is there a better way to zero out Calendar date?

I'm looking to see if there is a better way in obtaining the same result as the following code:
Calendar date = Calendar.getInstance();
date.setTimeInMillis(System.currentTimeMillis());
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
I'm using this to be able to compare the difference in days between two dates. I am currently coding for target API 24 and am not interested in using Joda Time for such a simple task.
I've come up with the following function, but would love to hear if there is a simpler, perhaps built in, method for either zeroing out the date or an entire different method for getting the amount of days between two dates.
private long getFlatDateInMillis() {
Calendar currentDate = Calendar.getInstance();
currentDate.setTimeInMillis(System.currentTimeMillis());
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
return currentDate.getTimeInMillis();
}
That way, I could quickly use:
Calendar date = getFlatDateInMillis();
I just want to make sure I'm not missing anything that is simpler, already pre-defined.
Thank you!
The correct way to do this is with the java.time.LocalDate class. It stores only the date, not the time, and it has a now() static method, which returns the current day.
LocalDate today = LocalDate.now();
If you're looking at Android, this was added at API level 26, but there are other ways of using the "new style" date classes with Android, such as the ThreeTen-Backport library.
tl;dr
ChronoUnit.DAYS.between( // Calculate elapsed time between a pair of `LocalDate` date-only objects. Returns a total number of elapsed days.
( (GregorianCalendar) myJavaUtilCal ) // Cast your legacy `java.util.Calendar` object to the subclass `java.util.GregorianCalendar`, also legacy.
.toZonedDateTime() // Convert from legacy `GregorianCalendar` to modern `ZonedDateTime` class.
.toLocalDate() , // Extract the date-only value, a `LocalDate`, lacking time-of-day and lacking time zone.
otherLocalDate // Compare to some other `LocalDate` object.
) // Returns a `long` number of days. Uses Half-Open approach where the beginning is *inclusive* while the ending is *exclusive*.
Details
The Answer by Kareem is correct. Some more thoughts here.
Is there a better way to zero out Calendar date?
Yes, there is a better way: don’t.
Trying to clear out the time-of-day on a date+time types is the wrong approach; use a date-only type instead (LocalDate).
And don’t use the troublesome old legacy classes such as Calendar, Date, SimpleDateFormat as they are now supplanted by the java.time classes.
the difference in days between two dates
First convert your legacy Calendar object to the modern ZonedDateTime class. To convert, call new methods added to the old classes.
GregorianCalendar myGregCal = (GregorianCalendar) myJavaUtilCal ; // Cast from superclass to subclass.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ; // Convert from legacy class to modern class.
Extract the date-only value.
LocalDate ld = zdt.toLocalDate() ; // Extract date-only object from date-time object.
Calculate elapsed time in days
long days = ChronoUnit.DAYS.between( ld , otherLd ) ;
Or represent the elapsed time as a Period.
Period p = Period.between( ld , otherLd ) ;
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.
EDIT: Thanks to Basil and Kareem, I've updated to the following code (so, so much easier):
Added to gradle.build:
compile 'com.jakewharton.threetenabp:threetenabp:1.0.5'
Then, in my activity, etc,
AndroidThreeTen.init(this);
LocalDate today = LocalDate.now();
LocalDate anotherDay = LocalDate.of(2019, 3, 25);
long dayDifference = ChronoUnit.DAYS.between(today, anotherDay); //dayDifference = 365
One thing of note is that Calendar references months starting at 0 index, whereas LocalDate references months starting at 1 index.

Converting timestamp to hours in java

I have the following timestamp stored in a long variable: 1471906800000 this stores the date 18/01/2017 00:00:00
I'm trying to create another timestamp that will contain the same date as stored in the first timestamp, but with the time being 23:59:59 -
I don't even know where to start
How could I achieve this in the most simple way possible in Java?
Thanks.
Using Calendar will help you:
long l = 1471906800000l;
Date date = new Date(l);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
l = calendar.calendar.getTimeInMillis();
Both of the other Answers use outmoded classes, now supplanted by the java.time classes.
Perhaps your input number is a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00Z). But I do not get the result you stated in the question.
long input = 1_471_906_800_000L ;
Instant instant = Instant.ofEpochMilli( input );
input: 1471906800000
instant: 2016-08-22T23:00:00Z
But you expected the value of 18/01/2017 00:00:00, off by a few months. If your input is not a count of milliseconds from 1970-01-01T00:00:00Z, you need to edit your Question to specify.
If you made a mistake in your expected output, then let's proceed to set the time-of-day.
If you wanted the second before the end of the day, I suggest subtracting a second from the start of the following day rather than hard-coding the time of 23:59:59. That time-of-day may be invalid because of anomalies such as Daylight Saving Time (DST). Also, unless you meant intend to work in UTC, you need to move into the desired/expected time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
Extract a LocalDate, for a date-only value without time-of-day and without time zone.
LocalDate ld = zdt.toLocalDate();
Move to next day.
LocalDate ldNextDay = ld.plusDays( 1 );
Ask for first moment.
ZonedDateTime zdtNextDay = ldNextDay.atStartOfDay( z );
Subtract a second to move back into previous day.
ZonedDateTime zdtPreviousDay = zdtNextDay.minusSeconds( 1L );
However, I suspect you are taking the wrong approach to handling date-time values. Rather than trying to determine the end of a day, I strongly suggest you follow the common practice of using the Half-Open approach to spans of time. In Half-Open, the beginning is inclusive while the ending is exclusive.
So a full day starts with the first moment of one day and runs up to, but not including, the first moment of the next day. This way you avoid the problem of the last second or trying to get the infinitely divisible fraction of a second.
ZonedDateTime zdtDayStart = LocalDate.of( 2017 , Month.JANUARY , 18 ).atStartOfDay( 1 );
ZonedDateTime zdtDayStop = zdtDayStart.plusDays( 1 );
You may find the Interval class in the ThreeTen-Extra project helpful.
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'm assuming that you don't specifically want the time at 23:59:59, but rather a time 1 minute before the start of the next day.
You should use a date/time library. I know jodatime better, so this example is written using that, but you may be able to use the Java 8 time API instead.
DateTime today = new DateTime(1471906800000L, TIME_ZONE);
// You may want to check that today is actually at the start of the day.
// e.g. today.equals(today.withTimeAtStartOfDay());
DateTime lastMinuteOfToday =
today.toLocalDate()
.plusDays(1)
.toDateTimeAtStartOfDay(TIME_ZONE)
.minusMinutes(1);
long lastMinuteOfTodayMillis = lastMinuteOfToday.getMillis();
Knowing the timezone is important to do this correctly.

What is the best way to retrieve the dates for last Monday and Friday

I need to get the dates for Monday and Friday last week. To do this, i am getting the date of Monday this week and subtracting 7 days. This gives me the date for Monday last week.
To get the date for Friday i have to add 4. This confused me a bit because for some reason the first day of the week is Sunday as opposed to Monday here in the UK.
Anyway, here is how i am getting the dates.
// Get the dates for last MON & FRI
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.add(Calendar.DAY_OF_WEEK, -7);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
// Get the date on Friday
cal.add(Calendar.DAY_OF_WEEK, 4);
cal.set(Calendar.HOUR_OF_DAY,23);
cal.set(Calendar.MINUTE,59);
cal.set(Calendar.SECOND,59);
cal.set(Calendar.MILLISECOND,0);
The above works but i am interested if there is anything wrong with the logic. I.e. will it work for Februarys, leap years etc.
Feel free to suggest a better solution/approach.
Thanks
tl;dr
get the dates for Monday and Friday last week
LocalDate // Represent a date only, without a time-of-day, and without a time zone or offset.
.now // Capture the current date as seen through the wall-clock time used by the people of a certain region (a time zone).
(
ZoneId.of( "America/Montreal" )
) // Returns a `LocalDate` object.
.with // Move to another date.
(
TemporalAdjusters.previous( DayOfWeek.MONDAY ) // Returns an implementation of the `TemporalAdjuster` interface.
) // Returns another `LocalDate` object, separate and distinct from our original `LocalDate` object. Per the immutable objects design pattern.
Avoid legacy date-time classes
The other Answers use the troublesome old legacy date-time classes now supplanted by the java.time questions.
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 provides for adjustments to move from one date-time value to another. Find handy implementations in the TemporalAdjusters class (note the plural 's'). The previous adjuster finds any specified object from the DayOfWeek enum.
The Question does not exactly define “last week”. Last seven days? Standard Monday-Sunday period? Localized week, such as Sunday-Saturday in the United States? The week prior to today’s week or including today’s partial week?
I will assume the prior seven days were intended.
LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) ) ;
LocalDate previousFriday = today.with( TemporalAdjusters.previous( DayOfWeek.FRIDAY ) ) ;
By the way, if you want to consider the initial date if it happens to already be the desired day-of-week, use alternate TemporalAdjuster implementations: previousOrSame or nextOrSame.
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.
Note: For Java 8 and above please take a look at Basil Bourque's answer (link).
Java 8 introduced a new time/date API which offers most of Joda-Time's functionality.
Joda-Time offers really nice methods for problems like that.
Getting the dates for Monday and Friday last week would look something like this using Joda Time:
DateTime today = DateTime.now();
DateTime sameDayLastWeek = today.minusWeeks(1);
DateTime mondayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.MONDAY);
DateTime fridayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.FRIDAY);
You can create DateTime objects from java.util.Date objects and vice versa so it is easy to use with Java dates.
Using the above code with the date
DateTime today = new DateTime("2012-09-30");
results in "2012-09-17" for Monday and "2012-09-21" for Friday, setting the date to
DateTime tomorrow = new DateTime("2012-10-01");
results in "2012-09-24" for Monday and "2012-09-28" for Friday.
You still have start of week set to sunday, which means that Calendar.MONDAY on a saturday is the monday before, while Calendar.MONDAY on a sunday is the next day.
What you need to do is (according to how you want it according to your comment above), to set the start of week to monday.
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.add(Calendar.DAY_OF_WEEK, -7);
...
Beyond that, and that the last second of friday isn't included in the range, your logic seems sound, and shouldn't have trouble with leap years/DST shifts etc.
The only thing I see wrong is that you are in fact testing the range Mo-Fr, and not, as stated, retrieving two specific days. It would be safer to test range Mo-Sa with exclusive upper bound.
You can use TemporalAdjusters to adjust the desired dates/days you are looking for.
Example:
LocalDate today = LocalDate.now();
LocalDate lastMonday = today.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
LocalDate lastFriday = today.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));

java get day of week is not accurate

I am trying to determine what day of the week is the first day of the month but for some reason it is not returning me the correct day of the week.
Here is my code below:
CalendarMonth[] months = CalendarUtils.constructMonthViewArray(new GregorianCalendar());
public static CalendarMonth[] constructMonthViewArray(Calendar cal) {
CalendarMonth[] months = new CalendarMonth[CALENDAR_GRID_SIZE];
int year = cal.get(cal.YEAR);
int month = cal.get(cal.MONTH);;
// calculate how many days in the month
int numOfDays = getNumOfDaysInMonth(cal);
// calculate what day(mon-sunday) is the 1st of the month
int firstDayOfMonth = getFirstDayOfMonth(cal);
private static int getFirstDayOfMonth(Calendar cal) {
int firstDay = cal.get(Calendar.DAY_OF_WEEK);
Log.d(TAG, "");
// decrement it because our array deals with values 0-6(indexes)
firstDay--;
if (firstDay == 0) {
firstDay = 6;
} else {
// decrement again so that the days start from 0.
firstDay--;
}
return firstDay;
}
The line from "int firstDay = cal.get(Calendar.DAY_OF_WEEK);" fails to give me the correct day of the week and returns the value 2 for getting the 1st day of this month(January 2011) when the first of the month was on a Saturday(7).
Am I missing something? I have debugged and checked what month, year and date the cal variable is set and it indeed indicated today's date as corrected but when i get the day of week it doesn't get the value 7.
I can't reproduce the problem you're seeing. As Michael says, there's a lot of code you haven't shown us, but Calendar.getDayOfWeek definitely works:
import java.util.*;
public class Test {
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar();
calendar.set(2011, 0, 1); // 0 = January
System.out.println(calendar.get(Calendar.DAY_OF_WEEK)); // Prints 7
}
}
Did you maybe forget that months are 0-based in java.util.Calendar?
If you can produce a similar short but complete program which shows the wrong day of the week, please post it.
The fact that you're decrementing firstDay twice within getFirstDayOfMonth seems somewhat odd, as well as the fact that it doesn't really reflect the name of the method (as Michael mentioned).
Finally, my constant recommendation for Java date/time handling: if you can possibly use Joda Time instead of java.util.Calendar, do so. It's a much, much better API.
The code of getFirstDayOfMonth() appears not to do what the method name says at all - but to actually understand what is happening, we need to see all the code that is involved, especially how the calendar initialized and the code of getNumOfDaysInMonth()
One thing to keep in mind: what is considered the first day of the week depends on the locale, as per getFirstDayOfWeek()
tl;dr
Convert from terrible legacy classes (Calendar, GregorianCalendar, etc.) to modern java.time classes (ZonedDateTime, LocalDate, etc.). Then get object for day-of-week, and ask it to automatically localize the name of that day of the week.
(GregorianCalendar) myJavaUtilCalendar // Cast your `Calendar` to `GregorianCalendar` assuming it actually is one.
.toZonedDateTime() // Convert from legacy class to modern class.
.toLocalDate() // Extract date-only object, without time-of-day and without time zone.
.with( // Adjust to another date by calling `TemporalAdjuster` implementation such as are found in `TemporalAdjusters` class.
TemporalAdjusters.firstDayOfMonth() // Adjust to the first day of the month.
) // Returns another `LocalDate` object, for the first of the month.
.getDayOfWeek() // Obtain a `DayOfWeek` enum object, one of seven pre-defined objects representing each day of the week.
.getDisplayName( // Automatically localize.
TextStyle.FULL , // Specify how long or abbreviated.
Locale.CANADA_FRENCH // Or `Locale.US` etc. to specify the human language and cultural norms to use in localizing.
) // Returns text in a `String` such as “Monday” or “lundi”.
java.time
The java.util.Calendar/.Date and related classes are a confusing mess as you have learned the hard way.
The modern approach uses java.time classes.
Conversion
If starting with a java.util.Calendar object, convert to java.time.
An Instant is a moment on the timeline in UTC.
Instant instant = myJavaUtilCalendarObject.toInstant();
Apply a time zone in order to get a date in order to get a day-of-week.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
Note that a time zone is critical in determining a date (and therefore day-of-week). "Today" is not the same date everywhere in the world simultaneously. A new day dawns earlier, for example, in Paris than in Montréal.
First Day Of Month
Let's move to the first of the month by calling withDayOfMonth.
ZonedDateTime zdtFirstOfMonth = zdt.withDayOfMonth(1);
Note that moving a date-time to first of month has issues. Anomalies such as Daylight Saving Time (DST) could have a surprising effect. Read the doc so you understand the behavior.
DayOfWeek
For day of week, use the well-named DayOfWeek enum.
DayOfWeek dayOfWeek = zdtFirstOfMonth.getDayOfWeek();
I suggest passing instances of this enum rather than a magic number like 2, 7, etc. But if you insist, you can extract an integer.
int dayOfWeekNumber = dayOfWeek.getValue();
To get a String of the name of day-of-week, let java.time generate a localized String via the getDisplayName method.
String output = dayOfWeek.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ); // Or Locale.ENGLISH
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.

Java: getMinutes and getHours

How do you get Hours and Minutes since Date.getHours and Date.getMinutes got deprecated? The examples that I found on Google search used the deprecated methods.
Try using Joda Time instead of standard java.util.Date classes. Joda Time library has much better API for handling dates.
DateTime dt = new DateTime(); // current time
int month = dt.getMonth(); // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day
See this question for pros and cons of using Joda Time library.
Joda Time may also be included to some future version of Java as a standard component, see JSR-310.
If you must use traditional java.util.Date and java.util.Calendar classes, see their JavaDoc's for help (java.util.Calendar and java.util.Date).
You can use the traditional classes like this to fetch fields from given Date instance.
Date date = new Date(); // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR); // gets hour in 12h format
calendar.get(Calendar.MONTH); // gets month number, NOTE this is zero based!
From the Javadoc for Date.getHours
As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)
So use
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
and the equivalent for getMinutes.
java.time
While I am a fan of Joda-Time, Java 8 introduces the java.time package which is finally a worthwhile Java standard solution! Read this article, Java SE 8 Date and Time, for a good amount of information on java.time outside of hours and minutes.
In particular, look at the LocalDateTime class.
Hours and minutes:
LocalDateTime.now().getHour();
LocalDateTime.now().getMinute();
First, import java.util.Calendar
Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
tl;dr
ZonedDateTime.now().getHour()
… or …
LocalTime.now().getHour()
ZonedDateTime
The Answer by J.D. is good but not optimal. That Answer uses the LocalDateTime class. Lacking any concept of time zone or offset-from-UTC, that class cannot represent a moment.
Better to use ZonedDateTime.
ZoneId z = ZoneID.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Specify time zone
If you omit the ZoneId argument, one is applied implicitly at runtime using the JVM’s current default time zone.
So this:
ZonedDateTime.now()
…is the same as this:
ZonedDateTime.now( ZoneId.systemDefault() )
Better to be explicit, passing your desired/expected time zone. The default can change at any moment during runtime.
If critical, confirm the time zone with the user.
Hour-minute
Interrogate the ZonedDateTime for the hour and minute.
int hour = zdt.getHour() ;
int minute = zdt.getMinute() ;
LocalTime
If you want just the time-of-day without the time zone, extract LocalTime.
LocalTime lt = zdt.toLocalTime() ;
Or skip ZonedDateTime entirely, going directly to LocalTime.
LocalTime lt = LocalTime.now( z ) ; // Capture the current time-of-day as seen in the wall-clock time used by the people of a particular region (a time zone).
java.time types
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 Calender. Use getInstance to get a Calender-Object. Then use setTime to set the required Date. Now you can use get(int field) with the appropriate constant like HOUR_OF_DAY or so to read the values you need.
http://java.sun.com/javase/6/docs/api/java/util/Calendar.html
One more way of getting minutes and hours is by using SimpleDateFormat.
SimpleDateFormat formatMinutes = new SimpleDateFormat("mm")
String getMinutes = formatMinutes.format(new Date())
SimpleDateFormat formatHours = new SimpleDateFormat("HH")
String getHours = formatHours.format(new Date())
int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();
These functions will return int values in hours and minutes.
I would recommend looking ad joda time.
http://www.joda.org/joda-time/
I was afraid of adding another library to my thick project, but it's just easy and fast and smart and awesome.
Plus, it plays nice with existing code, to some extent.
public static LocalTime time() {
LocalTime ldt = java.time.LocalTime.now();
ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
System.out.println(ldt);
return ldt;
}
This works for me
While I wouldn't recommend doing so, I think it's worth pointing out that although many methods on java.util.Date have been deprecated, they do still work. In trivial situations, it may be OK to use them. Also, java.util.Calendar is pretty slow, so getMonth and getYear on Date might be be usefully quicker.
Get hour from Date variable (yourdate):
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
import java.util.*You can gethour and minute using calendar and formatter class. Calendar cal = Calendar.getInstance() and Formatter fmt=new Formatter() and set a format for display hour and minute fmt.format("%tl:%M",cal,cal)and print System.out.println(fmt) output shows like 10:12

Categories