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
Related
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.
I have the following function:
public static Date getFirstOfLastMonth() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
How would I write a unit test to check the value returned by this function is the same as the expected value without using the same logic to generate the expected value?
See other answer for recommendation to use JodaTime or Java 8. However this can be done using java.util.Calendar.
The key is to change your method to pass in the date rather than let it assume the current time. Perhaps consider renaming this method too to reflect its new semantics, see Andreas suggestion of getFirstOfPreviousMonth.
You would need to call this as getFirstOfLastMonth(new Date()) to preserve existing behaviour, perhaps even with default method
public static Date getFirstOfLastMonth() {
return getFirstOfPreviousMonth(new Date());
}
public static Date getFirstOfPreviousMonth(Date now) {
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
Then some tests, you can use Calendar to inspect the result:
#Test
public void previousYear() {
Calendar input = Calendar.getInstance();
input.clear();
input.set(2009, Calendar.JANUARY, 5);
Date result = getFirstOfLastMonth(input.getTime());
Calendar output = Calendar.getInstance();
output.setTime(result);
assertThat(output.get(Calendar.YEAR), is(2008));
assertThat(output.get(Calendar.MONTH), is(Calendar.DECEMBER));
assertThat(output.get(Calendar.DAY_OF_MONTH), is(1));
}
Add a method that requires a timestamp to be passed in:
static Date getFirstOfPreviousMonth(long timeInMillis)
{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis( timeInMillis );
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
Now you can test this method by passing specific moments.
And the original method, implement it by calling this package private method with current system time.
public static Date getFirstOfLastMonth() {
getFirstOfPreviousMonth(System.currentTimeMillis());
}
The Answer by Adam is correct and should be accepted.
It mentions that you should be (really should be) using the modern java.time classes rather than the troublesome old legacy date-time classes. Here is a version of Adam's code adapted to the java.time classes.
Also, time zone is crucial in determining a date like first of month. For any given moment, the date varies around the globe by zone. For example, a new day dawns earlier in Auckland NZ than Montréal Québec. If omitted, your JVM implicitly applies its current default time zone. That default can change at any moment during runtime. Better to specify explicitly.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
ZonedDateTime
This Instant class is a basic building-block class of java.time. You can think of OffsetDateTime as an Instant plus a ZoneOffset. Likewise, you can think of ZonedDateTime as an Instant plus a ZoneId.
If you care only about the date and not the time-of-day, use LocalDate class.
TemporalAdjuster
The TemporalAdjuster interface defines classes for manipulating date-time values such as getting first-of-month. The TemporalAdjusters class (note the plural 's') provides implementations such as firstDayOfMonth.
public static ZonedDateTime getFirstOfLastMonth( ZoneId z ) {
Instant instant = Instant.now();
return getFirstOfPreviousMonth( instant , z );
}
public static ZonedDateTime getFirstOfPreviousMonth( Instant instantArg , ZoneId zoneArg ) {
ZonedDateTime zdt = instantArg.atZone( zoneArg);
ZonedDateTime firstOfMonthZdt = zdt.with( TemporalAdjusters.firstDayOfMonth() );
ZonedDateTime firstOfMonthPriorZdt = firstOfMonthZdt.minusMonths( 1 );
return firstOfMonthPriorZdt;
}
Clock
You can pass a special Clock implementation for testing rather than use by default the real-life-time clock implementation. That clock offers static methods to generate several such alternate implementations.
For example, the fixed implementation always supplies the same frozen moment in time. Let's say you wanted the clock to always report the first moment of March 21, 2017 in Québec time.
LocalDate ld = LocalDate.of( 2017 , Month.MARCH , 21 );
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ld.atStartOfDay( z ); // Let java.time determine first moment of the day. Not always `00:00:00`.
Instant instant = zdt.toInstant();
Clock c = Clock.fixed( instant , z );
// Pass this clock `c` in your calls to various java.time methods.
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 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.
Use Joda or Java 8 libraries. Java <= 7 is very deficient in this way. What you need to do is get underneath Calendar and mock it into thinking the date is some fixed date in time, like May 31st, 2010 or any other. Then your unit test uses hardcoded dates.
There's a bit of a long-winded way to do this with Calendar.
Your method cannot be static.
Your class constructor will take a CalendarFactory that returns calendars and will call factory.get() instead of Calendar.getInstance().
In your test code you will inject a CalendarFactory that outputs a calendar that has already had .set(someFixedDate) called on it.
Then you will unit test against fixed dates.
Believe it or not this is actually what good OO testable code looks like. In my opinion one of the best accomplishments of OO is it lets the developer express testable code. A static method will not make the cut here though, sorry.
I found this funny behavior while using Date and Calendar class to handle Exponential distributions for simulating arrival time at a store (academic work). The code is quite simple and is below displayed. Well suppose that "this.currentDate" is "Feb 15 08:00:00 BRST 2014".
If i shift forward the time 24h (parameter iSeconds=86.400), what is supposed to return ? The expected string would be "2014-02-16 08:00:00" but instead the time is shortened in 1h and the result is "2014-02-16 07:00:00", I wonder if someone could explain why my one hour was "stolen". No big deal, but since my next arrival time depends of the earlier one, it makes a mess over my time baseline shifting all of them one hour as well.
I thought could be some TZ issue, but heck, i just moved 24h in the middle of February.
public String shiftTimeStamp( int iSeconds)
{
Calendar cal = Calendar.getInstance();
cal.setTime(this.currentDate);
cal.add(Calendar.SECOND, iSeconds);
this.currentDate = cal.getTime();
String sTS = new SimpleDateFormat(SCSimLabels.DATE_TS_FORMAT).format(this.currentDate);
return sTS;
}
Note: Daylight Saving Time issue :) BRT <--> BRST tz.
my workaround: I just want a beacon to guide the time jumps caused by inter arrival times and I´m not interested on such calendar specificities, so when I need to move to the first work hour of the next day I just force the time to be 08:00:00 after 1 day shift. It works like a charm :)
Calendar cal = Calendar.getInstance();
cal.setTime(this.currentDate);
cal.add(Calendar.DATE, 1);
String sDate = (new SimpleDateFormat("yyyy-MM-dd 08:00:00")).format(cal.getTime());
Date newDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sDate);
this.currentDate = newDate;
Change the format call to this:
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(this.currentDate);
To see what timezone the format call is using. I bet the call to .add() is modifying the Calendar object's timezone since it crosses the standard time / daylight time border.
If this is the case, you could try adding a Calendar.DAY,1 or simply .setTimeZone(...) of the Calendar obj. back to the original timezone after the .add call.
Avoid legacy date-time classes
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Using java.time
If you want to work with generic 24-hour days without any time zone or offset-from-UTC, use the LocalDateTime class. If you always want to start at 8 AM, specify a LocalTime.
LocalDate ld = LocalDate.of( 2014 , Month.FEBRUARY , 15 ) ;
LocalTime lt = LocalTime.of( 8 , 0 ) ; // Specify hour in 24-hour clock, 0-23.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
Represent your 24 hour span as a Duration.
Duration d = Duration.ofHours( 24 );
LocalDateTime ldtLater = ldt.plus( d );
If you want to work with specific moments on the timeline as seen through the lens of a region’s particular wall-clock time, then specify a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Sao_Paulo" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
ZonedDateTime zdtLater = zdt.plus( d );
Note that adding 24 hours to a ZonedDateTime is not the same thing as adding a day. As you have learned the hard way, anomalies such as Daylight Saving Time (DST) means a day may be 23, 24, or 25 hours long, or even other lengths. So if you want to add a day and let java.time apply its logic to arrive at an appropriate time-of-day while taking into consideration anomalies such as DST, add days rather than hours.
ZonedDateTime zdtLater = zdt.plusDays( 1 );
Or add a Period of one whole day rather than a Duration of 24 hours.
Period p = Period.ofDays( 1 );
ZonedDateTime zdtLater = zdt.plus( p );
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.
I store a number of rows in DB with the timestamp of that moment in milliseconds.
Now if I need to retrieve all rows of a given day, like today, how do I correctly create the starting and ending milliseconds of that day?
I know about SimpleDateFormat and Calendar.getInstance() briefly, but would I need to do string manipulation (which I want to avoid) to get todays date only, add the hours part and then convert it back into milliseconds, or is there a better way to do it?
Since you didn't provide any code in your question, please allow me to give you a general answer in response..
What you're looking for are two date/times, today and tomorrow, both specified a "0 hours, 0 minutes, 0 seconds".
today <= date AND date < tomorrow
Note the two different comparisons.
The simplest technique would be to use DateFormat:
String input = "Sat Feb 17 2013";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
String input1="Sun Feb 18 2013"
Date inputNextDay = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long millisecondsForNextDay=inputNextDay.getTime();
To get the rows that fall on a particular day, just find rows having milliseconds value of timestamp between milliseconds and millisecondsForNextDay:
if(rowsTimestampSeconds>milliseconds && rowsTimestampSeconds<millisecondsForNextDay){
//get the row
}
You can use the GregorianCalendar class to do this without any strings.
Calendar calendar = new GregorianCalendar(year, month, day);
long start_of_day_millis = calendar.getTimeInMillis();
calendar.add(Calendar.DAY_OF_MONTH, 1);
long next_day_millis = calendar.getTimeInMillis();
The reason to use calendar.add(Calendar.DAY_OF_MONTH); instead of just adding (24*60*60*1000) to the first millisecond value is to account for leaps. Beyond the commonly known leap year, there are occurrences of leap seconds. See this link: http://www.timeanddate.com/time/leapseconds.html
Make sure that your expression is inclusive of start_of_day_millis (greater than or equal) and exlusive of next_day_millis (lesser than).
i.e: if(test_time >= start_of_day_millis && test_time < next_day_millis)
Update:
If you want today's date you can omit all the parameters in the calendar constructor and just call new GregorianCalendar(), but you will need to ensure that the hour, minute, second and millisecond fields are being zeroed out with calls to calendar.set(Calendar._FIELD_NAME_, 0); afterwards, before you use the calendar, because it would be initialized to the exact moment the object is created.
You should be using a date-time type for your database column to store date-time data rather than an integer of milliseconds. The SQL standard defines a few date-time types. But support for date-time varies widely, with Postgres being one of the best.
Since you tagged Java, read this Question and my Answer to learn about using Java to pinpoint the first moment of today and tomorrow. The Half-Open approach used there is common in date-time work. Half-Open means a span of time where the beginning is inclusive while the ending is exclusive. For SQL, it means not using the BETWEEN operator.
java.time
The java.time framework is built into Java 8 and later, and back-ported to Java 6 & 7 and to Android. Read my other Answer for details.
Get the first moments of today and tomorrow. Be aware that time zone is crucial in determining dates and the meaning of “today”. For any given moment, the date varies around the world by time zone. A new day begins earlier in the east. For example, a few moments after midnight in Paris is still “yesterday” in Montréal.
Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
ZonedDateTime zdtStart = zdt.toLocalDate().atStartOfDay( zoneId );
ZonedDateTime zdtTomorrowStart = zdtStart.plusDays( 1 );
Some day we may see JDBC drivers updated to directly handle java.time types. Indeed, JDBC 4.2 compliant drivers may work if you call getObject and setObject on your ResultSet and PreparedStatement respectively. But if not, fallback to using the java.sql types. Notice the new methods added to these old classes including java.sql.Timestamp. The from method takes an Instant which we can extract from our ZonedDateTime objects.
java.sql.Timestamp tsStart = java.sql.Timestamp.from( zdtStart.toInstant() );
java.sql.Timestamp tsStop = java.sql.Timestamp.from( zdtTomorrowStart.toInstant() );
Now set these two variables are arguments on your PreparedStatement. Notice the comparison operators, testing for possible values that start on first moment of the day (>=) and running up to but not including the first moment of the next day (<).
String sql =
"SELECT * FROM event_" +
"WHERE when_ >= ? " +
"AND when_ < ? " +
";" ;
…
pstmt.setTimestamp( 1 , tsStart );
pstmt.setTimestamp( 2 , tsStop );
If you do indeed store integers instead of using date-time types, and you are storing milliseconds as a count from the epoch reference date-time of first moment of 1970 in UTC, then you can extract a number from each Instant. Remember that the java.time classes use a finer resolution of nanoseconds as do some databases such as H2 Database, and some databases such as Postgres capture date-time with a resolution of microseconds. So truncating to milliseconds may mean a loss of data.
long millisStart = tsStart.toInstant().toEpochMilli();
long millisStop = tsStop.toInstant().toEpochMilli();
Call setLong on your PreparedStatement.
pstmt.setLong( 1 , millisStart );
pstmt.setLong( 2 , millisStop );
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.
How do I get the month as an integer from a Date object (java.util.Date)?
java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
java.time (Java 8)
You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();
Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.
But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.
If you use Java 8 date api, you can directly get it in one line!
LocalDate today = LocalDate.now();
int month = today.getMonthValue();
Joda-Time
Alternatively, with the Joda-Time DateTime class.
//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))
…or…
int month = dateTime.getMonthOfYear();
tl;dr
myUtilDate.toInstant() // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
.atZone( // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object.
ZoneId.of( "America/Montreal" ) // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMonthValue() // Extract a month number. Returns a `int` number.
java.time Details
The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.
I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.
Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.
The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.
To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth();
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
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….
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.
If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :
Note: Make sure your date is allready made by the format : dd/MM/YYYY
/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
return Integer.parseInt(dateFormat.format(date));
}
/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
return Integer.parseInt(dateFormat.format(date));
}
If we use java.time.LocalDate api, we can get month number in integer in single line:
import java.time.LocalDate;
...
int currentMonthNumber = LocalDate.now().getMonthValue(); //OR
LocalDate scoringDate = LocalDate.parse("2022-07-01").getMonthValue(); //for String date
For example today's date is 29-July-2022, output will be 7.
Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1
The returned value starts from 0, so you should add one to the result.