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

JavaDateCalendarSimpledateformatjava.util.date

Java Problem Overview


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!

Java Solutions


Solution 1 - Java

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));

Solution 2 - Java

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

Solution 3 - Java

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;
}

Solution 4 - Java

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());

Solution 5 - Java

This is incorrectly specified:

SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mm");

You're using minutes instead of month (MM)

Solution 6 - Java

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.

Solution 7 - Java

There's an error in the pattern of your SimpleDateFormat. it should be

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

Solution 8 - Java

use this format,

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

mm for minutes and MM for mounth

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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)

Solution 12 - Java

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])
}

Solution 13 - Java

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjunaidpView Question on Stackoverflow
Solution 1 - JavaAravind YarramView Answer on Stackoverflow
Solution 2 - JavaAlireza AlallahView Answer on Stackoverflow
Solution 3 - JavajeznagView Answer on Stackoverflow
Solution 4 - JavaMarco MontelView Answer on Stackoverflow
Solution 5 - JavaDawoodView Answer on Stackoverflow
Solution 6 - JavaBasil BourqueView Answer on Stackoverflow
Solution 7 - JavaBaldrickView Answer on Stackoverflow
Solution 8 - JavaKushanView Answer on Stackoverflow
Solution 9 - JavaDavid MiguelView Answer on Stackoverflow
Solution 10 - JavaMarek ManduchView Answer on Stackoverflow
Solution 11 - JavaSamuel IvanView Answer on Stackoverflow
Solution 12 - JavaOscar Emilio Perez MartinezView Answer on Stackoverflow
Solution 13 - JavatawheedView Answer on Stackoverflow