How to add minutes to my Date

后端 未结 12 1263
长发绾君心
长发绾君心 2020-11-30 22:11

I have this date object:

SimpleDateFormat df = new SimpleDateFormat(\"yyyy-mm-dd HH:mm\");
Date d1 = df.parse(interviewList.get(37).getTime());
相关标签:
12条回答
  • 2020-11-30 22:43

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

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    
    0 讨论(0)
  • 2020-11-30 22:49

    use this format,

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

    mm for minutes and MM for mounth

    0 讨论(0)
  • 2020-11-30 22:49

    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
    }
    
    0 讨论(0)
  • 2020-11-30 22:50

    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.

    0 讨论(0)
  • 2020-11-30 22:53

    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
    
    0 讨论(0)
  • 2020-11-30 22:58

    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)
    
    0 讨论(0)
提交回复
热议问题