How to obtain the start time and end time of a day? - java

How to obtain the start time and end time of a day?
code like this is not accurate:
private Date getStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.set(year, month, day, 0, 0, 0);
return calendar.getTime();
}
private Date getEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.set(year, month, day, 23, 59, 59);
return calendar.getTime();
}
It is not accurate to the millisecond.

Java 8
public static Date atStartOfDay(Date date) {
LocalDateTime localDateTime = dateToLocalDateTime(date);
LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
return localDateTimeToDate(startOfDay);
}
public static Date atEndOfDay(Date date) {
LocalDateTime localDateTime = dateToLocalDateTime(date);
LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
return localDateTimeToDate(endOfDay);
}
private static LocalDateTime dateToLocalDateTime(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
private static Date localDateTimeToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
Update: I've added these 2 methods to my Java Utility Classes here
DateUtils.atStartOfDay
DateUtils.atEndOfDay
It is in the Maven Central Repository at:
<dependency>
<groupId>com.github.rkumsher</groupId>
<artifactId>utils</artifactId>
<version>1.3</version>
</dependency>
Java 7 and Earlier
With Apache Commons
public static Date atEndOfDay(Date date) {
return DateUtils.addMilliseconds(DateUtils.ceiling(date, Calendar.DATE), -1);
}
public static Date atStartOfDay(Date date) {
return DateUtils.truncate(date, Calendar.DATE);
}
Without Apache Commons
public Date atEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
public Date atStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}

tl;dr
LocalDate // Represents an entire day, without time-of-day and without time zone.
.now( // Capture the current date.
ZoneId.of( "Asia/Tokyo" ) // Returns a `ZoneId` object.
) // Returns a `LocalDate` object.
.atStartOfDay( // Determines the first moment of the day as seen on that date in that time zone. Not all days start at 00:00!
ZoneId.of( "Asia/Tokyo" )
) // Returns a `ZonedDateTime` object.
Start of day
Get the full length of the today as seen in a time zone.
Using Half-Open approach, where the beginning is inclusive while the ending is exclusive. This approach solves the flaw in your code that fails to account for the very last second of the day.
ZoneId zoneId = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( zoneId ) ;
ZonedDateTime zdtStart = today.atStartOfDay( zoneId ) ;
ZonedDateTime zdtStop = today.plusDays( 1 ).atStartOfDay( zoneId ) ;
zdtStart.toString() = 2020-01-30T00:00+01:00[Africa/Tunis]
zdtStop.toString() = 2020-01-31T00:00+01:00[Africa/Tunis]
See the same moments in UTC.
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
start.toString() = 2020-01-29T23:00:00Z
stop.toString() = 2020-01-30T23:00:00Z
If you want the entire day of a date as seen in UTC rather than in a time zone, use OffsetDateTime.
LocalDate today = LocalDate.now( ZoneOffset.UTC ) ;
OffsetDateTime odtStart = today.atTime( OffsetTime.MIN ) ;
OffsetDateTime odtStop = today.plusDays( 1 ).atTime( OffsetTime.MIN ) ;
odtStart.toString() = 2020-01-30T00:00+18:00
odtStop.toString() = 2020-01-31T00:00+18:00
These OffsetDateTime objects will already be in UTC, but you can call toInstant if you need such objects which are always in UTC by definition.
Instant start = odtStart.toInstant() ;
Instant stop = odtStop.toInstant() ;
start.toString() = 2020-01-29T06:00:00Z
stop.toString() = 2020-01-30T06:00:00Z
Tip: You may be interested in adding the ThreeTen-Extra library to your project to use its Interval class to represent this pair of Instant objects. This class offers useful methods for comparison such as abuts, overlaps, contains, and more.
Interval interval = Interval.of( start , stop ) ;
interval.toString() = 2020-01-29T06:00:00Z/2020-01-30T06:00:00Z
Half-Open
The answer by mprivat is correct. His point is to not try to obtain end of a day, but rather compare to "before start of next day". His idea is known as the "Half-Open" approach where a span of time has a beginning that is inclusive while the ending is exclusive.
The current date-time frameworks of Java (java.util.Date/Calendar and Joda-Time) both use milliseconds from the epoch. But in Java 8, the new JSR 310 java.time.* classes use nanoseconds resolution. Any code you wrote based on forcing the milliseconds count of last moment of day would be incorrect if switched to the new classes.
Comparing data from other sources becomes faulty if they employ other resolutions. For example, Unix libraries typically employ whole seconds, and databases such as Postgres resolve date-time to microseconds.
Some Daylight Saving Time changes happen over midnight which might further confuse things.
Joda-Time 2.3 offers a method for this very purpose, to obtain first moment of the day: withTimeAtStartOfDay(). Similarly in java.time, LocalDate::atStartOfDay.
Search StackOverflow for "joda half-open" to see more discussion and examples.
See this post, Time intervals and other ranges should be half-open, by Bill Schneider.
Avoid legacy date-time classes
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
Use java.time classes. The java.time framework is the official successor of the highly successful Joda-Time library.
java.time
The java.time framework is built into Java 8 and later. Back-ported to Java 6 & 7 in the ThreeTen-Backport project, further adapted to Android in the ThreeTenABP project.
An Instant is a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Apply a time zone to get the wall-clock time for some locality.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
To get the first moment of the day go through the LocalDate class and its atStartOfDay method.
ZonedDateTime zdtStart = zdt.toLocalDate().atStartOfDay( zoneId );
Using Half-Open approach, get first moment of following day.
ZonedDateTime zdtTomorrowStart = zdtStart.plusDays( 1 );
Currently the java.time framework lacks an Interval class as described below for Joda-Time. However, the ThreeTen-Extra project extends java.time with additional classes. This project is the proving ground for possible future additions to java.time. Among its classes is Interval. Construct an Interval by passing a pair of Instant objects. We can extract an Instant from our ZonedDateTime objects.
Interval today = Interval.of( zdtStart.toInstant() , zdtTomorrowStart.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. 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….
Joda-Time
UPDATE: The Joda-Time project is now in maintenance-mode, and advises migration to the java.time classes. I am leaving this section intact for history.
Joda-Time has three classes to represent a span of time in various ways: Interval, Period, and Duration. An Interval has a specific beginning and ending on the timeline of the Universe. This fits our need to represent "a day".
We call the method withTimeAtStartOfDay rather than set time of day to zeros. Because of Daylight Saving Time and other anomalies the first moment of the day may not be 00:00:00.
Example code using Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( timeZone );
DateTime todayStart = now.withTimeAtStartOfDay();
DateTime tomorrowStart = now.plusDays( 1 ).withTimeAtStartOfDay();
Interval today = new Interval( todayStart, tomorrowStart );
If you must, you can convert to a java.util.Date.
java.util.Date date = todayStart.toDate();

in getEndOfDay, you can add:
calendar.set(Calendar.MILLISECOND, 999);
Although mathematically speaking, you can't specify the end of a day other than by saying it's "before the beginning of the next day".
So instead of saying, if(date >= getStartOfDay(today) && date <= getEndOfDay(today)), you should say: if(date >= getStartOfDay(today) && date < getStartOfDay(tomorrow)). That is a much more solid definition (and you don't have to worry about millisecond precision).

java.time
Using java.time framework built into Java 8.
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); // 2015-11-19T19:42:19.224
// start of a day
now.with(LocalTime.MIN); // 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); // 2015-11-19T00:00
// end of a day
now.with(LocalTime.MAX); // 2015-11-19T23:59:59.999999999

Java 8 or ThreeTenABP
ZonedDateTime
ZonedDateTime curDate = ZonedDateTime.now();
public ZonedDateTime startOfDay() {
return curDate
.toLocalDate()
.atStartOfDay()
.atZone(curDate.getZone())
.withEarlierOffsetAtOverlap();
}
public ZonedDateTime endOfDay() {
ZonedDateTime startOfTomorrow =
curDate
.toLocalDate()
.plusDays(1)
.atStartOfDay()
.atZone(curDate.getZone())
.withEarlierOffsetAtOverlap();
return startOfTomorrow.minusSeconds(1);
}
// based on https://stackoverflow.com/a/29145886/1658268
LocalDateTime
LocalDateTime curDate = LocalDateTime.now();
public LocalDateTime startOfDay() {
return curDate.atStartOfDay();
}
public LocalDateTime endOfDay() {
return startOfTomorrow.atTime(LocalTime.MAX); //23:59:59.999999999;
}
// based on https://stackoverflow.com/a/36408726/1658268
I hope that helps someone.

Additional way of finding start of day with java8 java.time.ZonedDateTime instead of going through LocalDateTime is simply truncating the input ZonedDateTime to DAYS:
zonedDateTimeInstance.truncatedTo( ChronoUnit.DAYS );

I tried this code and it works well!
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final ZonedDateTime startofDay =
now.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTime endOfDay =
now.toLocalDate().atTime(LocalTime.MAX).atZone(ZoneOffset.UTC);

For java 8 the following single line statements are working. In this example I use UTC timezone. Please consider to change TimeZone that you currently used.
System.out.println(new Date());
final LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
final Date endOfDayAsDate = Date.from(endOfDay.toInstant(ZoneOffset.UTC));
System.out.println(endOfDayAsDate);
final LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
final Date startOfDayAsDate = Date.from(startOfDay.toInstant(ZoneOffset.UTC));
System.out.println(startOfDayAsDate);
If no time difference with output. Try: ZoneOffset.ofHours(0)

Another one solution which does not depend on any framework is:
static public Date getStartOfADay(Date day) {
final long oneDayInMillis = 24 * 60 * 60 * 1000;
return new Date(day.getTime() / oneDayInMillis * oneDayInMillis);
}
static public Date getEndOfADay(Date day) {
final long oneDayInMillis = 24 * 60 * 60 * 1000;
return new Date((day.getTime() / oneDayInMillis + 1) * oneDayInMillis - 1);
}
Note that it returns UTC based time

I know it's a bit late, but in case of Java 8, if you are using OffsetDateTime (which offers a lot of advantages, such as TimeZone, Nanoseconds, etc.), you can use the following code:
OffsetDateTime reallyEndOfDay = someDay.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
// output: 2019-01-10T23:59:59.999999999Z

private Date getStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.setTimeInMillis(0);
calendar.set(year, month, day, 0, 0, 0);
return calendar.getTime();
}
private Date getEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.setTimeInMillis(0);
calendar.set(year, month, day, 23, 59, 59);
return calendar.getTime();
}
calendar.setTimeInMillis(0); gives you accuracy upto milliseconds

Shortest answer, given your timezone being TZ:
LocalDateTime start = LocalDate.now(TZ).atStartOfDay()
LocalDateTime end = start.plusDays(1)
Compare using isAfter() and isBefore() methods, or convert it using toEpochSecond() or toInstant() methods.

The following code takes the OP's original formula, and adjusts for the ms inexactness:
private static Date getStartOfDay() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.set(year, month, day, 0, 0, 0);
long approximateTimestamp = calendar.getTime().getTime();
long extraMillis = (approximateTimestamp % 1000);
long exactTimestamp = approximateTimestamp - extraMillis;
return new Date(exactTimestamp);
}
private static Date getEndOfDay() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.set(year, month, day, 23, 59, 59);
long approximateTimestamp = calendar.getTime().getTime();
long extraMillis = (approximateTimestamp % 1000);
long exactTimestamp = approximateTimestamp - extraMillis + 999;
return new Date(exactTimestamp);
}
Unlike many other answers on this thread, it is compatible with older versions of Java and Android APIs.

I had several inconveniences with all the solutions because I needed the type of Instant variable and the Time Zone always interfered changing everything, then combining solutions I saw that this is a good option.
LocalDate today = LocalDate.now();
Instant startDate = Instant.parse(today.toString()+"T00:00:00Z");
Instant endDate = Instant.parse(today.toString()+"T23:59:59Z");
and we have as a result
startDate = 2020-01-30T00:00:00Z
endDate = 2020-01-30T23:59:59Z
I hope it helps you

I think the easiest would be something like:
// Joda Time
DateTime dateTime=new DateTime();
StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();
These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.

public static Date beginOfDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date endOfDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
}

Date date = new Date();
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
Timestamp:
Timestamp startTs = Timestamp.valueOf(startOfDay);
Timestamp endTs = Timestamp.valueOf(endOfDay);

Related

How to set Calendar object to current date but time from SimpleDateFormat that contains HH:mm:ss

I need to create a new Calendar object that contains the current date but the time needs to be set from a given String of format HH:mm:ss.
I create a new calendar object with current date and time and then use a SimpleDateFormat object to parse the string and set the time from that one but that only overwrites the calendar object with the parsed time and Jan 1 1970:
def currentTime = new java.util.Date();
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(currentTime);
java.util.Date inTime = new SimpleDateFormat("HH:mm:ss").parse(initialTime);
calendar1.setTime(inTime);
Is there a way to get the values of Hour, Minute, Seconds and Milliseconds from the Date object to use it with calendar.set(Calendar.HOUR_OF_DAY, hour), etc.?
tl;dr
GregorianCalendar.from( // Converting from modern java.time class to troublesome legacy class. Do so only if you must. Otherwise use only the java.time classes.
ZonedDateTime.of( // Modern java.time class representing a moment, a point on the timeline, with an assigned time zone through which to see the wall-clock time used by the people of a particular region.
LocalDate.now( ZoneId.of( “Pacific/Auckland” ) ) , // The current date in a particular time zone. For any given moment, the date varies around the globe by zone.
LocalTime.of( 12 , 34 , 56 ) , // Specify your desired time-of-day.
ZoneId.of( “Pacific/Auckland” ) // Assign a time zone for which the date and time is intended.
)
)
java.time
The modern approach uses the java.time classes.
ZoneId z = ZoneId.of( “America/Montreal” ) ;
LocalDate ld = LocalDate.now( z ) ;
LocalTime lt = LocalTime.of( 12 , 34 , 56 ) ; // 12:34:56
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
You can extract the time-of-day (or date) from an existing ZonedDateTime.
LocalTime lt = zdt.toLocalTime() ;
LocalDate ld = zdt.toLocalDate() ;
Best to avoid the troublesome old legacy date-time classes added before Java 8. But if you must, you can convert between the modern and legacy classes. Call on new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ; // If you must, but better to avoid the troublesome old legacy classes.
Not sure if this helps you.
String hhmmss = "10:20:30";
String[] parts = hhmmss.split(":");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal.set(Calendar.SECOND, Integer.parseInt(parts[2]));
Calendar objet Time is a java.util.Date object with the standard format. You can not set date with a specific format to your calendar.
To get the Date details (Hours, Minutes ...) try :
final Date date = new Date(); // your date
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
final int year = cal.get(Calendar.YEAR);
final int month = cal.get(Calendar.MONTH);
final int day = cal.get(Calendar.DAY_OF_MONTH);
final int hour = cal.get(Calendar.HOUR_OF_DAY);
final int minute = cal.get(Calendar.MINUTE);
final int second = cal.get(Calendar.SECOND);

How to get starting date and end date of year in Android?

I need help in getting start and end date of current year, last year and next year.
Below is my code: this code is work fine for month, can I modify it for year?
Note: this code is only for example.
protected void getDataByMonths(int currentDayOfMonth) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month;
if (currentDayOfMonth >= 2) {
month = calendar.get(Calendar.MONTH) + 1;
} else {
month = calendar.get(Calendar.MONTH) - currentDayOfMonth;
}
int day = 1;
calendar.set(year, month, day);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
String firstday = String.valueOf(df.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth - 1);
String lastday = String.valueOf(df.format(calendar.getTime()));
String result = getButtonName(button) + " From :" + getDateInMonthFormat(firstday) + " " + "To :" + getDateInMonthFormat(lastday);
finalcontacts = mySqliteDBhelper.getContactsBetweenRange(button, getDateInMilliseconds(firstday), getDateInMilliseconds(lastday));
finalstatus.setText(result);
}
Assuming that you cannot use Java 8, here is how it could be done:
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Create first day of year
Calendar firstDayOfCurrentYear = Calendar.getInstance();
firstDayOfCurrentYear.set(Calendar.DATE, 1);
firstDayOfCurrentYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfCurrentYear.getTime()));
// Create last day of year
Calendar lastDayOfCurrentYear = Calendar.getInstance();
lastDayOfCurrentYear.set(Calendar.DATE, 31);
lastDayOfCurrentYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfCurrentYear.getTime()));
// Create first day of next year
Calendar firstDayOfNextYear = Calendar.getInstance();
firstDayOfNextYear.add(Calendar.YEAR, 1);
firstDayOfNextYear.set(Calendar.DATE, 1);
firstDayOfNextYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfNextYear.getTime()));
// Create last day of next year
Calendar lastDayOfNextYear = Calendar.getInstance();
lastDayOfNextYear.add(Calendar.YEAR, 1);
lastDayOfNextYear.set(Calendar.DATE, 31);
lastDayOfNextYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfNextYear.getTime()));
Output:
01/01/2016
12/31/2016
01/01/2017
12/31/2017
Check this:
public static String GetYearSlot(int option,String inputDate)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy",java.util.Locale.getDefault());
Date myDate = null;
try
{
myDate = sdf.parse(inputDate);
}
catch(Exception ex)
{
ex.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.YEAR, option);
calendar.set(Calendar.DAY_OF_YEAR, 1);
Date YearFirstDay = calendar.getTime();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
Date YearLastDay = calendar.getTime();
return sdf.format(YearFirstDay)+"-"+sdf.format(YearLastDay);
}
how to use:
GetYearSlot(1, fromDate): it gives you next year from the date you passed(input 1)
GetYearSlot(0, fromDate): it gives you current year from the date you passed(input 0)
GetYearSlot(-1, fromDate): it gives you previous year from the date you passed(input -1)
java.time
You are using troublesome old legacy date-time classes now supplanted by the java.time classes.
First get the current date.
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 );
Use Year to represent the entire year as an object.
Year thisYear = Year.from( today );
Year nextYear = thisYear.plusYears( 1 );
Year lastYear = thisYear.minusYears( 1 );
Usually in date-time work we represent a span of time using the Half-Open approach. In this approach the beginning is inclusive while the ending is exclusive. So a year would start on January first and run up to, but not include, January 1 of the following year.
If on Java 8, you could include the ThreeTen-Extra project and its Interval class to represent the span of time.
Otherwise do it yourself.
LocalDate thisYearStart = thisYear.atDay( 1 );
LocalDate lastYearStart = lastYear.atDay( 1 );
LocalDate nextYearStart = nextYear.atDay( 1 );
If you truly need the last day of the year, you could just subtract one day from the first day of the following year. Even easier is using a TemporalAdjuster defined in TemporalAdjusters class.
LocalDate thisYearFirstDay = today.with( TemporalAdjusters.firstDayOfYear() );
LocalDate thisYearLastDay = today.with( TemporalAdjusters.lastDayOfYear() );
LocalDate nextYearFirstDay = thisYearLastDay.plusDays( 1 );
LocalDate nextYearLastDay = nextYearFirstDay.with( TemporalAdjusters.lastDayOfYear() );
LocalDate lastYearLastDay = thisYearFirstDay.minusDays( 1 );
LocalDate lastYearFirstDay = lastYearLastDay.with( TemporalAdjusters.firstDayOfYear() );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (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.

How to get next month start date and end date if current month is february? [duplicate]

This question already has answers here:
How to get the first date and last date of the previous month? (Java)
(9 answers)
Closed 4 years ago.
String febSt = "02/01/2014" ;
String febEnd = "02/28/2014" ;
Above code is my input i need "03/01/2014" and "03/31/2014" as output .
I tried more codes and used calendar functions also but no result.From this program i need next month start and end date .
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class MonthCalculation {
public void getNextMonth(String date) throws ParseException{
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date dt = format.parse(date);
Date begining, end;
{
Calendar calendar = getCalendarForNow(dt);
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
SimpleDateFormat endDt = new SimpleDateFormat("MM/dd/yyyy");
String endStrDt = endDt.format(end);
if(date != null && date.equalsIgnoreCase(endStrDt)){
System.out.println("Ending of the month");
calendar.add(Calendar.DAY_OF_MONTH, 1);
Date lastDate = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String lastDateofNextMonth = sdf.format(lastDate);
System.out.println("Next Month :"+lastDateofNextMonth);
Calendar c = getCalendarForNow(new Date(lastDateofNextMonth));
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
SimpleDateFormat sfd = new SimpleDateFormat("MM/dd/yyyy");
String lastDated = endDt.format(end);
System.out.println("Testing side :"+lastDated);
}else if (findLeapYear(dt)){
Calendar calendar3 = getCalendarForNow(dt);
calendar3.add(Calendar.YEAR, 1);
Date ds = calendar3.getTime();
SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
String dates = dtft.format(ds);
dtft.setLenient(false);
System.out.println("YEAR : "+dates);
}else{
SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar2 = getCalendarForNow(dt);
System.out.println(" Calendar time :->> " + dtft.format(calendar2.getTime()));
int curre_month = calendar2.get(Calendar.MONTH);
int curre_day = calendar2.get(Calendar.DAY_OF_MONTH);
int curre_year = calendar2.get(Calendar.YEAR);
Date dat = calendar2.getTime();
calendar2.add(Calendar.DATE, 31);
Date ds = calendar2.getTime();
String dates = dtft.format(ds);
dtft.setLenient(false);
System.out.println("OTHER DAYS : "+dates);
}
}
}
private static boolean findLeapYear(Date dt){
boolean isLeapYr = false;
int yr = dt.getYear();
if ((yr%4 == 0 && yr%100!=0)){
isLeapYr = true;
}
return isLeapYr;
}
private static Calendar getCalendarForNow(Date dt) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(dt);
return calendar;
}
private static void setTimeToBeginningOfDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
}
private static void setTimeToEndofDay(Calendar calendar) {
System.out.println("For feb calling");
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}
public static void main(String[] args) {
try {
String janSt = "01/01/2014" ;
String janEnd = "01/31/2014" ;
String febSt = "02/01/2014" ;
String febEnd = "02/28/2014" ;
String marSt = "03/01/2014" ;
String marEnd = "03/31/2014" ;
String aprilSt = "04/01/2014" ;
String aprilEnd = "04/30/2014" ;
String maySt = "05/01/2014" ;
String mayEnd = "05/31/2014" ;
String juneSt = "06/01/2014" ;
String juneEnd = "06/30/2014" ;
String julySt = "07/01/2014" ;
String julyEnd = "07/31/2014" ;
String augSt = "08/01/2014" ;
String augEnd = "08/31/2014" ;
String sepSt = "09/01/2014" ;
String sepEnd = "09/30/2014" ;
String octSt = "10/01/2014" ;
String octEnd = "10/31/2014" ;
String novSt = "11/01/2014" ;
String novEnd = "11/30/2014" ;
String deceSt = "12/01/2014" ;
String deceEnd = "12/31/2014" ;
String jan15St="01/01/2015";
String jan15End="01/31/2015";
String leapyr = "02/29/2016";
String notaleapyr = "02/28/2015";
new MonthCalculation().getNextMonth(febSt);
} catch (ParseException e) {
e.printStackTrace();
}
}
I tried more with sample inputs , for the months February ,april, june nov start date are not working if i pass these dates as inputs it returns with 2nd of next month
Suggest any idea to proceed further.I am struggling this code.
Thanks in advance
Try this:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
tl;dr
LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
.with( TemporalAdjusters.firstDayOfNextMonth() )
…and…
LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
.with( TemporalAdjusters.lastDayOfMonth() )
java.time
The modern way is with the new java.time package bundled with Java 8 (inspired by Joda-Time, defined by JSR 310).
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeformatter.ofPattern( "MM/dd/uuuu" );
LocalDate ld = LocalDate.parse( "02/14/2014" , f );
The TemporalAdjuster interface defines a way for implementations to manipulate date-time values. The TemporalAdjusters class provides several handy implementations.
LocalDate firstOfMonth = ld.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate firstOfNextMonth = ld.with( TemporalAdjusters.firstDayOfNextMonth() );
The Question asks for the first and last of the following month, March in this case. We have the first of next month, so we just need the end of that month.
LocalDate lastOfNextMonth = firstOfNextMonth.with( TemporalAdjusters.lastDayOfMonth() );
By the way, as discussed below, the best practice for defining a span of time is the Half-Open approach. That means a month is the first of the month and running up to, but not including, the first of the month after. In this approach we do not bother with determining the last day of the month.
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Easy when using the Joda-Time library and its LocalDate class.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "02/14/2014" );
LocalDate firstOfMonth = localDate.withDayOfMonth( 1 );
LocalDate nextMonth = localDate.plusMonths(1); // Use this for "half-open" range.
LocalDate endOfMonth = nextMonth.minusDays(1); // Use this for "fully-closed" range.
Half-Open
Tip: Rather than focus on the last moment of a span of time, a better practice is to use the "Half-Open" approach.
In half-open, the beginning is inclusive and the ending is exclusive. So for "a month", we start with the first of the desired month and run up to, but not including, the first of the next month.
February 2014 = 2014-02-01/2014-03-01
Span Of Time
Be aware that Joda-Time provides three handy classes for handling a span of time: Interval, Period, and Duration.
These classes work only with date-time objects (DateTime class) rather than the date-only (LocalDate class) shown in code above.
While not directly relevant to your question, I suspect these span-of-time classes may be 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.
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.
Something I quickly wrote for you - so could be cleaned up. Check if this helps:
String string = "02/01/2014"; //assuming input
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date dt = sdf .parse(string);
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.MONTH, 1); //adding a month directly - gives the start of next month.
String firstDate = sdf.format(c.getTime());
System.out.println(firstDate);
//get last day of the month - add month, substract a day.
c.add(Calendar.MONTH, 1);
c.add(Calendar.DAY_OF_MONTH, -1);
String lastDate = sdf.format(c.getTime());
System.out.println(lastDate);
since it is hard to get in your code I have write some coe for you. please check it out..
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today : " + sdf.format(today));
System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));
I see the question is old. But I used the DateUtils static methods ceiling and truncate. Came in pretty handy instead of using multiple lines of code.
Date today = new Date();
DateUtils.truncate(new Date(), Calendar.MONTH) // Thu Dec 01 00:00:00 EET 2016
DateUtils.ceiling(new Date(), Calendar.MONTH) // Sun Jan 01 00:00:00 EET 2017

Compare if a date is less than 24 hours before

I am trying to compare two calendars in java to decide if one of them is >= 24 hours ago. I am unsure on the best approach to accomplish this.
// get today's date
Date today = new Date();
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(today);
// get last update date
Date lastUpdate = profile.getDateLastUpdated().get(owner);
Calendar lastUpdatedCalendar = Calendar.getInstance();
lastUpdatedCalendar(lastUpdate);
// compare that last hotted was < 24 hrs ago from today?
tl;dr
Instant now = Instant.now();
Boolean isWithinPrior24Hours =
( ! yourJUDate.toInstant().isBefore( now.minus( 24 , ChronoUnit.HOURS) ) )
&&
( yourJUDate.toInstant().isBefore( now )
) ;
Details
The old date-time classes (java.util.Date/.Calendar, java.text.SimpleDateFormat, etc.) have proven to be be confusing and flawed. Avoid them.
For Java 8 and later, use java.time framework built into Java. For earlier Java, add the Joda-Time framework to your project.
You can easily convert between a java.util.Date and either framework.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The Instant class represents a moment on the timeline in UTC. If you meant to ask for literally 24 hours rather than "a day", then Instant is all we need.
Instant then = yourJUDate.toInstant();
Instant now = Instant.now();
Instant twentyFourHoursEarlier = now.minus( 24 , ChronoUnit.HOURS );
// Is that moment (a) not before 24 hours ago, AND (b) before now (not in the future)?
Boolean within24Hours = ( ! then.isBefore( twentyFourHoursEarlier ) ) && then.isBefore( now ) ;
If you meant "a day" rather than 24 hours, then we need to consider time zone. A day is determined locally, within a time zone. Daylight Saving Time (DST) and other anomalies mean a day is not always 24 hours long.
Instant then = yourJUDate.toInstant();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
ZonedDateTime oneDayAgo = now.minusDays( 1 );
Boolean within24Hours = ( ! then.isBefore( oneDayAgo ) ) && then.isBefore( now ) ;
Another approach would use the Interval class found in the ThreeTen-Extra project. That class represents a pair of Instant objects. The class offers methods such as contains to perform comparisons.
Joda-Time
The Joda-Time library works in a similar fashion to java.time, having been its inspiration.
DateTime dateTime = new DateTime( yourDate ); // Convert java.util.Date to Joda-Time DateTime.
DateTime yesterday = DateTime.now().minusDays(1);
boolean isBeforeYesterday = dateTime.isBefore( yesterday );
Or, in one line:
boolean isBeforeYesterday = new DateTime( yourDate).isBefore( DateTime.now().minusDays(1) );
you could use Date.getTime(), here's an example:
public final static long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
public static void main(String args[]) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2009-12-31");
Date date2 = sdf.parse("2010-01-31");
boolean moreThanDay = Math.abs(date1.getTime() - date2.getTime()) > MILLIS_PER_DAY;
System.out.println(moreThanDay);
}
You can check localDateTime whether its in 24 hours or not, depending on zone offset parameter like following the example.
#Test
public void checkIsWithin24Hours() {
final ZoneOffset zoneOffset = ZoneOffset.UTC;
final LocalDateTime now = LocalDateTime.now(zoneOffset);
final LocalDateTime after = LocalDateTime.now(zoneOffset).plusHours(5);
final long nowHours = TimeUnit.MILLISECONDS.toHours(now.toInstant(zoneOffset).toEpochMilli());
final long afterFiveHours = TimeUnit.MILLISECONDS.toHours(after.toInstant(zoneOffset).toEpochMilli());
assertThat(afterFiveHours - nowHours <= 24).isTrue();
}

Why is the month changed to 50 after I added 10 minutes?

I have this date object:
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mm");
Date d1 = df.parse(interviewList.get(37).getTime());
value of d1 is Fri Jan 07 17:40:00 PKT 2011
Now I am trying to add 10 minutes to the date above.
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
Value of newTime changes to 2011-50-07 17:50
but it should be 07-01-2011 17:50.
It adds minutes correctly but it also changes month, don't know why!
The issue for you is that you are using mm. You should use MM. MM is for month and mm is for minutes. Try with yyyy-MM-dd HH:mm
Other approach:
It can be as simple as this (other option is to use joda-time)
static final long ONE_MINUTE_IN_MILLIS=60000;//millisecs
Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date afterAddingTenMins=new Date(t + (10 * ONE_MINUTE_IN_MILLIS));
you can use DateUtils class in org.apache.commons.lang3.time package
int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute
Convenience method for implementing #Pangea's answer:
/*
* Convenience method to add a specified number of minutes to a Date object
* From: http://stackoverflow.com/questions/9043981/how-to-add-minutes-to-my-date
* #param minutes The number of minutes to add
* #param beforeTime The time that will have minutes added to it
* #return A date object with the specified number of minutes added to it
*/
private static Date addMinutesToDate(int minutes, Date beforeTime){
final long ONE_MINUTE_IN_MILLIS = 60000;//millisecs
long curTimeInMs = beforeTime.getTime();
Date afterAddingMins = new Date(curTimeInMs + (minutes * ONE_MINUTE_IN_MILLIS));
return afterAddingMins;
}
In order to avoid any dependency you can use java.util.Calendar as follow:
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, 10);
Date teenMinutesFromNow = now.getTime();
In Java 8 we have new API:
LocalDateTime dateTime = LocalDateTime.now().plus(Duration.of(10, ChronoUnit.MINUTES));
Date tmfn = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
This is incorrectly specified:
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mm");
You're using minutes instead of month (MM)
tl;dr
LocalDateTime.parse(
"2016-01-23 12:34".replace( " " , "T" )
)
.atZone( ZoneId.of( "Asia/Karachi" ) )
.plusMinutes( 10 )
java.time
Use the excellent java.time classes for date-time work. These classes supplant the troublesome old date-time classes such as java.util.Date and java.util.Calendar.
ISO 8601
The java.time classes use standard ISO 8601 formats by default for parsing/generating strings of date-time values. To make your input string comply, replace the SPACE in the middle with a T.
String input = "2016-01-23 12:34" ;
String inputModified = input.replace( " " , "T" );
LocalDateTime
Parse your input string as a LocalDateTime as it lacks any info about time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( inputModified );
Add ten minutes.
LocalDateTime ldtLater = ldt.plusMinutes( 10 );
ldt.toString(): 2016-01-23T12:34
ldtLater.toString(): 2016-01-23T12:44
See live code in IdeOne.com.
That LocalDateTime has no time zone, so it does not represent a point on the timeline. Apply a time zone to translate to an actual moment. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland, or Asia/Karachi. Never use the 3-4 letter abbreviation such as EST or IST or PKT as they are not true time zones, not standardized, and not even unique(!).
ZonedDateTime
If you know the intended time zone for this value, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Karachi" );
ZonedDateTime zdt = ldt.atZone( z );
zdt.toString(): 2016-01-23T12:44+05:00[Asia/Karachi]
Anomalies
Think about whether to add those ten minutes before or after adding a time zone. You may get a very different result because of anomalies such as Daylight Saving Time (DST) that shift the wall-clock time.
Whether you should add the 10 minutes before or after adding the zone depends on the meaning of your business scenario and rules.
Tip: When you intend a specific moment on the timeline, always keep the time zone information. Do not lose that info, as done with your input data. Is the value 12:34 meant to be noon in Pakistan or noon in France or noon in Québec? If you meant noon in Pakistan, say so by including at least the offset-from-UTC (+05:00), and better still, the name of the time zone (Asia/Karachi).
Instant
If you want the same moment as seen through the lens of UTC, extract an 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).
Instant instant = zdt.toInstant();
Convert
Avoid the troublesome old date-time classes whenever possible. But if you must, you can convert. Call new methods added to the old classes.
java.util.Date utilDate = java.util.Date.from( instant );
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.
There's an error in the pattern of your SimpleDateFormat. it should be
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
use this format,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
mm for minutes and MM for mounth
Once you have you date parsed, I use this utility function to add hours, minutes or seconds:
public class DateTimeUtils {
private static final long ONE_HOUR_IN_MS = 3600000;
private static final long ONE_MIN_IN_MS = 60000;
private static final long ONE_SEC_IN_MS = 1000;
public static Date sumTimeToDate(Date date, int hours, int mins, int secs) {
long hoursToAddInMs = hours * ONE_HOUR_IN_MS;
long minsToAddInMs = mins * ONE_MIN_IN_MS;
long secsToAddInMs = secs * ONE_SEC_IN_MS;
return new Date(date.getTime() + hoursToAddInMs + minsToAddInMs + secsToAddInMs);
}
}
Be careful when adding long periods of time, 1 day is not always 24 hours (daylight savings-type adjustments, leap seconds and so on), Calendar is recommended for that.
Can be done without the constants (like 3600000 ms is 1h)
public static Date addMinutesToDate(Date date, int minutes) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minutes);
return calendar.getTime();
}
public static Date addHoursToDate(Date date, int hours) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hours);
return calendar.getTime();
}
example of usage:
System.out.println(new Date());
System.out.println(addMinutesToDate(new Date(), 5));
Tue May 26 16:16:14 CEST 2020
Tue May 26 16:21:14 CEST 2020
Work for me DateUtils
//import
import org.apache.commons.lang.time.DateUtils
...
//Added and removed minutes to increase current range dates
Date horaInicialCorteEspecial = DateUtils.addMinutes(new Date(corteEspecial.horaInicial.getTime()),-1)
Date horaFinalCorteEspecial = DateUtils.addMinutes(new Date(corteEspecial.horaFinal.getTime()),1)
For android developers, here's a kotlin implementation using an extension of #jeznag's answer
fun Date.addMinutesToDate(minutes: Int): Date {
val minuteMillis: Long = 60000 //millisecs
val curTimeInMs: Long = this.time
val result = Date(curTimeInMs + minutes * minuteMillis)
this.time = result.time
return this
}
an unit test to check functionality works as expected
#Test
fun `test minutes are added to date`() {
//given
val date = SimpleDateFormat("dd-MM-yyyy hh:mm").parse("29-04-2021 23:00")
//when
date?.addMinutesToDate(45)
//then
val calendar = Calendar.getInstance()
calendar.time = date
assertEquals(29, calendar[Calendar.DAY_OF_MONTH])
assertEquals(23, calendar[Calendar.HOUR_OF_DAY])
assertEquals(45, calendar[Calendar.MINUTE])
}
Just for anybody who is interested. I was working on an iOS project that required similar functionality so I ended porting the answer by #jeznag to swift
private func addMinutesToDate(minutes: Int, beforeDate: NSDate) -> NSDate {
var SIXTY_SECONDS = 60
var m = (Double) (minutes * SIXTY_SECONDS)
var c = beforeDate.timeIntervalSince1970 + m
var newDate = NSDate(timeIntervalSince1970: c)
return newDate
}

Categories