问题
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!
回答1:
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));
回答2:
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
回答3:
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;
}
回答4:
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());
回答5:
This is incorrectly specified:
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mm");
You're using minutes instead of month (MM)
回答6:
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.
回答7:
There's an error in the pattern of your SimpleDateFormat. it should be
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
回答8:
use this format,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
mm for minutes and MM for mounth
回答9:
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.
回答10:
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)
回答11:
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
}
来源:https://stackoverflow.com/questions/9043981/how-to-add-minutes-to-my-date