Adding n hours to a date in Java?Android Add 2 hours to date StringAdding time in hours to a date object in java?Time not addingGetting entries from Parse.com of maximum 1 hour difference between current time and added timeJava that adds timeWhat's the difference between Instant and LocalDateTime?How to convert ZonedDateTime to Date?How to use ThreeTenABP in Android ProjectConvert java.util.Date to what “java.time” type?Adding seconds to a DateIs Java “pass-by-reference” or “pass-by-value”?Avoiding != null statementsHow do I read / convert an InputStream into a String in Java?Add days to JavaScript DateHow to add 30 minutes to a JavaScript Date object?Detecting an “invalid date” Date instance in JavaScriptHow do I get the current date in JavaScript?Calculate difference between two dates (number of days)?Sort ArrayList of custom Objects by propertyHow to format a JavaScript date

What is the need of methods like GET and POST in the HTTP protocol?

Two trains move towards each other, a bird moves between them. How many trips can the bird make?

Writing a letter of recommendation for a mediocre student

Why did UK NHS pay for homeopathic treatments?

How do I deal with too many NPCs in my campaign?

Is the mass of paint relevant in rocket design?

Why does this image of Jupiter look so strange?

Does wetting a beer glass change the foam characteristics?

Was there a trial by combat between a man and a dog in medieval France?

What is the meaning of "heutig" in this sentence?

Can a broken/split chain be reassembled?

What can a pilot do if an air traffic controller is incapacitated?

Resolving moral conflict

Is this a Sherman, and if so what model?

Where Does VDD+0.3V Input Limit Come From on IC chips?

Is it true that, "just ten trading days represent 63 per cent of the returns of the past 50 years"?

Strange Sticky Substance on Digital Camera

Why does NASA publish all the results/data it gets?

Title Change now and Wage Increase Later

Worms crawling under skin

Is it a good idea to leave minor world details to the reader's imagination?

Understanding Portugal addresses

2000s Animated TV show where teenagers could physically go into a virtual world

What benefits does the Power Word Kill spell have?



Adding n hours to a date in Java?


Android Add 2 hours to date StringAdding time in hours to a date object in java?Time not addingGetting entries from Parse.com of maximum 1 hour difference between current time and added timeJava that adds timeWhat's the difference between Instant and LocalDateTime?How to convert ZonedDateTime to Date?How to use ThreeTenABP in Android ProjectConvert java.util.Date to what “java.time” type?Adding seconds to a DateIs Java “pass-by-reference” or “pass-by-value”?Avoiding != null statementsHow do I read / convert an InputStream into a String in Java?Add days to JavaScript DateHow to add 30 minutes to a JavaScript Date object?Detecting an “invalid date” Date instance in JavaScriptHow do I get the current date in JavaScript?Calculate difference between two dates (number of days)?Sort ArrayList of custom Objects by propertyHow to format a JavaScript date






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








130















How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.










share|improve this question





















  • 3





    Use joda-time.sourceforge.net, if possible.

    – Babar
    Aug 27 '10 at 5:03






  • 3





    Use Java 8 Date and Time if possible.

    – peceps
    Aug 18 '16 at 14:12












  • @Babar FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

    – Basil Bourque
    Mar 25 '18 at 18:49

















130















How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.










share|improve this question





















  • 3





    Use joda-time.sourceforge.net, if possible.

    – Babar
    Aug 27 '10 at 5:03






  • 3





    Use Java 8 Date and Time if possible.

    – peceps
    Aug 18 '16 at 14:12












  • @Babar FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

    – Basil Bourque
    Mar 25 '18 at 18:49













130












130








130


20






How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.










share|improve this question
















How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.







java date






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 15 '14 at 18:57









Reimius

5,3124 gold badges20 silver badges41 bronze badges




5,3124 gold badges20 silver badges41 bronze badges










asked Aug 27 '10 at 4:07









Jorge LainfiestaJorge Lainfiesta

6512 gold badges5 silver badges3 bronze badges




6512 gold badges5 silver badges3 bronze badges










  • 3





    Use joda-time.sourceforge.net, if possible.

    – Babar
    Aug 27 '10 at 5:03






  • 3





    Use Java 8 Date and Time if possible.

    – peceps
    Aug 18 '16 at 14:12












  • @Babar FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

    – Basil Bourque
    Mar 25 '18 at 18:49












  • 3





    Use joda-time.sourceforge.net, if possible.

    – Babar
    Aug 27 '10 at 5:03






  • 3





    Use Java 8 Date and Time if possible.

    – peceps
    Aug 18 '16 at 14:12












  • @Babar FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

    – Basil Bourque
    Mar 25 '18 at 18:49







3




3





Use joda-time.sourceforge.net, if possible.

– Babar
Aug 27 '10 at 5:03





Use joda-time.sourceforge.net, if possible.

– Babar
Aug 27 '10 at 5:03




3




3





Use Java 8 Date and Time if possible.

– peceps
Aug 18 '16 at 14:12






Use Java 8 Date and Time if possible.

– peceps
Aug 18 '16 at 14:12














@Babar FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

– Basil Bourque
Mar 25 '18 at 18:49





@Babar FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

– Basil Bourque
Mar 25 '18 at 18:49












15 Answers
15






active

oldest

votes


















201
















Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.



 Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date()); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
cal.getTime(); // returns new date object, one hour in the future


Check API for more.






share|improve this answer




















  • 4





    Just be careful if you're dealing with daylight savings/summer time.

    – CurtainDog
    Aug 27 '10 at 4:26






  • 4





    Needless to mention you can add "negative hours"

    – pramodc84
    Aug 27 '10 at 5:56






  • 6





    @CurtainDog Using Calendar.add() takes care of that automatically.

    – Jesper
    Aug 27 '10 at 10:05






  • 5





    cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale."

    – mithrandir
    Dec 10 '14 at 9:54











  • FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

    – Basil Bourque
    Mar 25 '18 at 18:48


















73
















If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():



Date newDate = DateUtils.addHours(oldDate, 3);


(The original object is unchanged)






share|improve this answer






















  • 2





    You can also use negativ Hours: DateUtils.addHours(oldDate, -1);

    – Kaptain
    Feb 24 '15 at 10:54












  • Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not?

    – Matt
    Feb 13 '18 at 16:01



















28
















To simplify @Christopher's example.



Say you have a constant



public static final long HOUR = 3600*1000; // in milli-seconds.


You can write.



Date newDate = new Date(oldDate.getTime() + 2 * HOUR);


If you use long to store date/time instead of the Date object you can do



long newDate = oldDate + 2 * HOUR;





share|improve this answer
































    24
















    tl;dr



    myJavaUtilDate.toInstant()
    .plusHours( 8 )


    Or…



    myJavaUtilDate.toInstant() // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
    .plus( // Do the math, adding a span of time to our moment, our `Instant`.
    Duration.ofHours( 8 ) // Specify a span of time unattached to the timeline.
    ) // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.


    Using java.time



    The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.



    Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.



    Instant instant = myUtilDate.toInstant();


    You can add hours to that Instant by passing a TemporalAmount such as Duration.



    Duration duration = Duration.ofHours( 8 );
    Instant instantHourLater = instant.plus( duration );


    To read that date-time, generate a String in standard ISO 8601 format by calling toString.



    String output = instantHourLater.toString();


    You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.



    ZoneId zoneId = ZoneId.of( "America/Montreal" );
    ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );


    Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.



    ZonedDateTime later = zdt.plusHours( 8 );


    You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.



    java.util.Date date = java.util.Date.from( later.toInstant() );


    For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.




    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, 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.






    share|improve this answer


































      23
















      With Joda-Time



      DateTime dt = new DateTime();
      DateTime added = dt.plusHours(6);





      share|improve this answer






















      • 2





        +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library

        – Joeri Hendrickx
        Aug 27 '10 at 8:16






      • 3





        @JoeriHendrickx If the programmer is adding hours to a date, then very likely they are doing other date-time work. I don’t consider Joda-Time unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new java.time.* package (inspired by Joda-Time) to Java 8.

        – Basil Bourque
        Feb 17 '14 at 6:14











      • I had trouble with Joda on android. Kept getting ClassNotDefinedException

        – TheRealChx101
        Nov 8 '15 at 17:39


















      22
















      Since Java 8:



      LocalDateTime.now().minusHours(1);


      See LocalDateTime API.






      share|improve this answer






















      • 4





        Close but not quite right. You should go for a ZonedDateTime rather than a LocalDateTime. The "Local" means not tied to any particular locality, and not tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See my Answer by comparison.

        – Basil Bourque
        Oct 8 '15 at 16:37






      • 1





        Also to get a java.util.Date object as requester had asked us ZonedDateTime.toInstant() and Date.from() as described here stackoverflow.com/a/32274725/5661065

        – hayduke
        Oct 18 '17 at 0:28


















      14
















      Something like:



      Date oldDate = new Date(); // oldDate == current time
      final long hoursInMillis = 60L * 60L * 1000L;
      Date newDate = new Date(oldDate().getTime() +
      (2L * hoursInMillis)); // Adds 2 hours





      share|improve this answer




















      • 1





        FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

        – Basil Bourque
        Mar 25 '18 at 18:48


















      14
















      Using the newish java.util.concurrent.TimeUnit class you can do it like this



       Date oldDate = new Date(); // oldDate == current time
      Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Adds 2 hours





      share|improve this answer
































        6
















        This is another piece of code when your Date object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.



         String myString = "09:00 12/12/2014";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
        Date myDateTime = null;

        //Parse your string to SimpleDateFormat
        try

        myDateTime = simpleDateFormat.parse(myString);

        catch (ParseException e)

        e.printStackTrace();

        System.out.println("This is the Actual Date:"+myDateTime);
        Calendar cal = new GregorianCalendar();
        cal.setTime(myDateTime);

        //Adding 21 Hours to your Date
        cal.add(Calendar.HOUR_OF_DAY, 21);
        System.out.println("This is Hours Added Date:"+cal.getTime());


        Here is the Output:



         This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
        This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014





        share|improve this answer

























        • You could also use: Calendar cal = Calendar.getInstance();

          – Stefan Sprenger
          Aug 21 '15 at 8:35


















        4
















        If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:



        import java.time.Duration;
        import java.time.LocalDateTime;

        ...

        LocalDateTime yourDate = ...

        ...

        // Adds 1 hour to your date.

        yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
        // OR
        yourDate = yourDate + Duration.parse("PT1H"); // Groovy.





        share|improve this answer






















        • 1





          Duration.parse(iso8601duration) is interesting, thanks, but you cannot use operator + on LocalDateTime, you might want to edit that. But .plus(...) does work.

          – qlown
          May 24 '17 at 22:42












        • Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly.

          – Daniel
          May 24 '17 at 22:49











        • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

          – Basil Bourque
          Mar 28 at 22:11











        • @BasilBourque Date object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out LocalDateTime for ZonedDateTime.

          – Daniel
          Mar 28 at 23:12



















        4
















        You can do it with Joda DateTime API



        DateTime date= new DateTime(dateObj);
        date = date.plusHours(1);
        dateObj = date.toDate();





        share|improve this answer



























        • Working after I changed the 1st line into DateTime dateTime= new DateTime(dateObj);

          – Sundararaj Govindasamy
          Jun 7 '17 at 19:49


















        3
















        Date argDate = new Date(); //set your date.
        String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
        String dateTime = sdf.format(argDate) + " " + argTime;
        Date requiredDate = dateFormat.parse(dateTime);





        share|improve this answer
































          0
















          by using Java 8 classes. we can manipulate date and time very easily as below.



          LocalDateTime today = LocalDateTime.now();
          LocalDateTime minusHours = today.minusHours(24);
          LocalDateTime minusMinutes = minusHours.minusMinutes(30);
          LocalDate localDate = LocalDate.from(minusMinutes);





          share|improve this answer

























          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

            – Basil Bourque
            Mar 28 at 22:08



















          0
















          You can use the LocalDateTime class from Java 8. For eg :



          long n = 4;
          LocalDateTime localDateTime = LocalDateTime.now();
          System.out.println(localDateTime.plusHours(n));





          share|improve this answer

























          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

            – Basil Bourque
            Mar 28 at 22:10


















          -1
















          You can use this method, It is easy to understand and implement :



          public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) 
          Calendar calendar = Calendar.getInstance();
          calendar.setTime(date);
          calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
          calendar.add(Calendar.MINUTE, nombreMinute);
          calendar.add(Calendar.SECOND, nombreSeconde);
          return calendar.getTime();






          share|improve this answer

























          • This approach is already presented in another Answer posted years ago. I do not see how this one adds anymore value.

            – Basil Bourque
            Jan 13 '17 at 17:37












          • The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :)

            – Nimpo
            Jan 15 '17 at 12:12













          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );














          draft saved

          draft discarded
















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3581258%2fadding-n-hours-to-a-date-in-java%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          15 Answers
          15






          active

          oldest

          votes








          15 Answers
          15






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          201
















          Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.



           Calendar cal = Calendar.getInstance(); // creates calendar
          cal.setTime(new Date()); // sets calendar time/date
          cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
          cal.getTime(); // returns new date object, one hour in the future


          Check API for more.






          share|improve this answer




















          • 4





            Just be careful if you're dealing with daylight savings/summer time.

            – CurtainDog
            Aug 27 '10 at 4:26






          • 4





            Needless to mention you can add "negative hours"

            – pramodc84
            Aug 27 '10 at 5:56






          • 6





            @CurtainDog Using Calendar.add() takes care of that automatically.

            – Jesper
            Aug 27 '10 at 10:05






          • 5





            cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale."

            – mithrandir
            Dec 10 '14 at 9:54











          • FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

            – Basil Bourque
            Mar 25 '18 at 18:48















          201
















          Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.



           Calendar cal = Calendar.getInstance(); // creates calendar
          cal.setTime(new Date()); // sets calendar time/date
          cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
          cal.getTime(); // returns new date object, one hour in the future


          Check API for more.






          share|improve this answer




















          • 4





            Just be careful if you're dealing with daylight savings/summer time.

            – CurtainDog
            Aug 27 '10 at 4:26






          • 4





            Needless to mention you can add "negative hours"

            – pramodc84
            Aug 27 '10 at 5:56






          • 6





            @CurtainDog Using Calendar.add() takes care of that automatically.

            – Jesper
            Aug 27 '10 at 10:05






          • 5





            cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale."

            – mithrandir
            Dec 10 '14 at 9:54











          • FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

            – Basil Bourque
            Mar 25 '18 at 18:48













          201














          201










          201









          Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.



           Calendar cal = Calendar.getInstance(); // creates calendar
          cal.setTime(new Date()); // sets calendar time/date
          cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
          cal.getTime(); // returns new date object, one hour in the future


          Check API for more.






          share|improve this answer













          Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.



           Calendar cal = Calendar.getInstance(); // creates calendar
          cal.setTime(new Date()); // sets calendar time/date
          cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
          cal.getTime(); // returns new date object, one hour in the future


          Check API for more.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 27 '10 at 4:11









          Nikita RybakNikita Rybak

          58.5k20 gold badges142 silver badges169 bronze badges




          58.5k20 gold badges142 silver badges169 bronze badges










          • 4





            Just be careful if you're dealing with daylight savings/summer time.

            – CurtainDog
            Aug 27 '10 at 4:26






          • 4





            Needless to mention you can add "negative hours"

            – pramodc84
            Aug 27 '10 at 5:56






          • 6





            @CurtainDog Using Calendar.add() takes care of that automatically.

            – Jesper
            Aug 27 '10 at 10:05






          • 5





            cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale."

            – mithrandir
            Dec 10 '14 at 9:54











          • FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

            – Basil Bourque
            Mar 25 '18 at 18:48












          • 4





            Just be careful if you're dealing with daylight savings/summer time.

            – CurtainDog
            Aug 27 '10 at 4:26






          • 4





            Needless to mention you can add "negative hours"

            – pramodc84
            Aug 27 '10 at 5:56






          • 6





            @CurtainDog Using Calendar.add() takes care of that automatically.

            – Jesper
            Aug 27 '10 at 10:05






          • 5





            cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale."

            – mithrandir
            Dec 10 '14 at 9:54











          • FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

            – Basil Bourque
            Mar 25 '18 at 18:48







          4




          4





          Just be careful if you're dealing with daylight savings/summer time.

          – CurtainDog
          Aug 27 '10 at 4:26





          Just be careful if you're dealing with daylight savings/summer time.

          – CurtainDog
          Aug 27 '10 at 4:26




          4




          4





          Needless to mention you can add "negative hours"

          – pramodc84
          Aug 27 '10 at 5:56





          Needless to mention you can add "negative hours"

          – pramodc84
          Aug 27 '10 at 5:56




          6




          6





          @CurtainDog Using Calendar.add() takes care of that automatically.

          – Jesper
          Aug 27 '10 at 10:05





          @CurtainDog Using Calendar.add() takes care of that automatically.

          – Jesper
          Aug 27 '10 at 10:05




          5




          5





          cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale."

          – mithrandir
          Dec 10 '14 at 9:54





          cal.setTime(new Date()) is not needed - the javadoc of Calendar.getInstance() says: "The Calendar returned is based on the current time in the default time zone with the default locale."

          – mithrandir
          Dec 10 '14 at 9:54













          FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

          – Basil Bourque
          Mar 25 '18 at 18:48





          FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

          – Basil Bourque
          Mar 25 '18 at 18:48













          73
















          If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():



          Date newDate = DateUtils.addHours(oldDate, 3);


          (The original object is unchanged)






          share|improve this answer






















          • 2





            You can also use negativ Hours: DateUtils.addHours(oldDate, -1);

            – Kaptain
            Feb 24 '15 at 10:54












          • Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not?

            – Matt
            Feb 13 '18 at 16:01
















          73
















          If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():



          Date newDate = DateUtils.addHours(oldDate, 3);


          (The original object is unchanged)






          share|improve this answer






















          • 2





            You can also use negativ Hours: DateUtils.addHours(oldDate, -1);

            – Kaptain
            Feb 24 '15 at 10:54












          • Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not?

            – Matt
            Feb 13 '18 at 16:01














          73














          73










          73









          If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():



          Date newDate = DateUtils.addHours(oldDate, 3);


          (The original object is unchanged)






          share|improve this answer















          If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():



          Date newDate = DateUtils.addHours(oldDate, 3);


          (The original object is unchanged)







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 29 '18 at 8:27









          Script47

          11.1k4 gold badges30 silver badges52 bronze badges




          11.1k4 gold badges30 silver badges52 bronze badges










          answered Aug 27 '10 at 4:40









          Sean Patrick FloydSean Patrick Floyd

          241k52 gold badges407 silver badges541 bronze badges




          241k52 gold badges407 silver badges541 bronze badges










          • 2





            You can also use negativ Hours: DateUtils.addHours(oldDate, -1);

            – Kaptain
            Feb 24 '15 at 10:54












          • Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not?

            – Matt
            Feb 13 '18 at 16:01













          • 2





            You can also use negativ Hours: DateUtils.addHours(oldDate, -1);

            – Kaptain
            Feb 24 '15 at 10:54












          • Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not?

            – Matt
            Feb 13 '18 at 16:01








          2




          2





          You can also use negativ Hours: DateUtils.addHours(oldDate, -1);

          – Kaptain
          Feb 24 '15 at 10:54






          You can also use negativ Hours: DateUtils.addHours(oldDate, -1);

          – Kaptain
          Feb 24 '15 at 10:54














          Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not?

          – Matt
          Feb 13 '18 at 16:01






          Behind the scenes, this does exactly what Nikita's answer does, but this is very simple and easy to read. Plus, if you already use Apache Commons / Lang... why not?

          – Matt
          Feb 13 '18 at 16:01












          28
















          To simplify @Christopher's example.



          Say you have a constant



          public static final long HOUR = 3600*1000; // in milli-seconds.


          You can write.



          Date newDate = new Date(oldDate.getTime() + 2 * HOUR);


          If you use long to store date/time instead of the Date object you can do



          long newDate = oldDate + 2 * HOUR;





          share|improve this answer





























            28
















            To simplify @Christopher's example.



            Say you have a constant



            public static final long HOUR = 3600*1000; // in milli-seconds.


            You can write.



            Date newDate = new Date(oldDate.getTime() + 2 * HOUR);


            If you use long to store date/time instead of the Date object you can do



            long newDate = oldDate + 2 * HOUR;





            share|improve this answer



























              28














              28










              28









              To simplify @Christopher's example.



              Say you have a constant



              public static final long HOUR = 3600*1000; // in milli-seconds.


              You can write.



              Date newDate = new Date(oldDate.getTime() + 2 * HOUR);


              If you use long to store date/time instead of the Date object you can do



              long newDate = oldDate + 2 * HOUR;





              share|improve this answer













              To simplify @Christopher's example.



              Say you have a constant



              public static final long HOUR = 3600*1000; // in milli-seconds.


              You can write.



              Date newDate = new Date(oldDate.getTime() + 2 * HOUR);


              If you use long to store date/time instead of the Date object you can do



              long newDate = oldDate + 2 * HOUR;






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Aug 27 '10 at 22:06









              Peter LawreyPeter Lawrey

              460k65 gold badges617 silver badges1006 bronze badges




              460k65 gold badges617 silver badges1006 bronze badges
























                  24
















                  tl;dr



                  myJavaUtilDate.toInstant()
                  .plusHours( 8 )


                  Or…



                  myJavaUtilDate.toInstant() // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
                  .plus( // Do the math, adding a span of time to our moment, our `Instant`.
                  Duration.ofHours( 8 ) // Specify a span of time unattached to the timeline.
                  ) // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.


                  Using java.time



                  The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.



                  Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.



                  Instant instant = myUtilDate.toInstant();


                  You can add hours to that Instant by passing a TemporalAmount such as Duration.



                  Duration duration = Duration.ofHours( 8 );
                  Instant instantHourLater = instant.plus( duration );


                  To read that date-time, generate a String in standard ISO 8601 format by calling toString.



                  String output = instantHourLater.toString();


                  You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.



                  ZoneId zoneId = ZoneId.of( "America/Montreal" );
                  ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );


                  Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.



                  ZonedDateTime later = zdt.plusHours( 8 );


                  You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.



                  java.util.Date date = java.util.Date.from( later.toInstant() );


                  For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.




                  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, 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.






                  share|improve this answer































                    24
















                    tl;dr



                    myJavaUtilDate.toInstant()
                    .plusHours( 8 )


                    Or…



                    myJavaUtilDate.toInstant() // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
                    .plus( // Do the math, adding a span of time to our moment, our `Instant`.
                    Duration.ofHours( 8 ) // Specify a span of time unattached to the timeline.
                    ) // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.


                    Using java.time



                    The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.



                    Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.



                    Instant instant = myUtilDate.toInstant();


                    You can add hours to that Instant by passing a TemporalAmount such as Duration.



                    Duration duration = Duration.ofHours( 8 );
                    Instant instantHourLater = instant.plus( duration );


                    To read that date-time, generate a String in standard ISO 8601 format by calling toString.



                    String output = instantHourLater.toString();


                    You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.



                    ZoneId zoneId = ZoneId.of( "America/Montreal" );
                    ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );


                    Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.



                    ZonedDateTime later = zdt.plusHours( 8 );


                    You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.



                    java.util.Date date = java.util.Date.from( later.toInstant() );


                    For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.




                    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, 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.






                    share|improve this answer





























                      24














                      24










                      24









                      tl;dr



                      myJavaUtilDate.toInstant()
                      .plusHours( 8 )


                      Or…



                      myJavaUtilDate.toInstant() // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
                      .plus( // Do the math, adding a span of time to our moment, our `Instant`.
                      Duration.ofHours( 8 ) // Specify a span of time unattached to the timeline.
                      ) // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.


                      Using java.time



                      The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.



                      Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.



                      Instant instant = myUtilDate.toInstant();


                      You can add hours to that Instant by passing a TemporalAmount such as Duration.



                      Duration duration = Duration.ofHours( 8 );
                      Instant instantHourLater = instant.plus( duration );


                      To read that date-time, generate a String in standard ISO 8601 format by calling toString.



                      String output = instantHourLater.toString();


                      You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.



                      ZoneId zoneId = ZoneId.of( "America/Montreal" );
                      ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );


                      Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.



                      ZonedDateTime later = zdt.plusHours( 8 );


                      You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.



                      java.util.Date date = java.util.Date.from( later.toInstant() );


                      For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.




                      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, 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.






                      share|improve this answer















                      tl;dr



                      myJavaUtilDate.toInstant()
                      .plusHours( 8 )


                      Or…



                      myJavaUtilDate.toInstant() // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
                      .plus( // Do the math, adding a span of time to our moment, our `Instant`.
                      Duration.ofHours( 8 ) // Specify a span of time unattached to the timeline.
                      ) // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.


                      Using java.time



                      The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.



                      Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.



                      Instant instant = myUtilDate.toInstant();


                      You can add hours to that Instant by passing a TemporalAmount such as Duration.



                      Duration duration = Duration.ofHours( 8 );
                      Instant instantHourLater = instant.plus( duration );


                      To read that date-time, generate a String in standard ISO 8601 format by calling toString.



                      String output = instantHourLater.toString();


                      You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.



                      ZoneId zoneId = ZoneId.of( "America/Montreal" );
                      ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );


                      Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.



                      ZonedDateTime later = zdt.plusHours( 8 );


                      You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.



                      java.util.Date date = java.util.Date.from( later.toInstant() );


                      For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.




                      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, 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.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Mar 25 '18 at 18:51

























                      answered Oct 8 '15 at 16:27









                      Basil BourqueBasil Bourque

                      135k38 gold badges448 silver badges635 bronze badges




                      135k38 gold badges448 silver badges635 bronze badges
























                          23
















                          With Joda-Time



                          DateTime dt = new DateTime();
                          DateTime added = dt.plusHours(6);





                          share|improve this answer






















                          • 2





                            +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library

                            – Joeri Hendrickx
                            Aug 27 '10 at 8:16






                          • 3





                            @JoeriHendrickx If the programmer is adding hours to a date, then very likely they are doing other date-time work. I don’t consider Joda-Time unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new java.time.* package (inspired by Joda-Time) to Java 8.

                            – Basil Bourque
                            Feb 17 '14 at 6:14











                          • I had trouble with Joda on android. Kept getting ClassNotDefinedException

                            – TheRealChx101
                            Nov 8 '15 at 17:39















                          23
















                          With Joda-Time



                          DateTime dt = new DateTime();
                          DateTime added = dt.plusHours(6);





                          share|improve this answer






















                          • 2





                            +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library

                            – Joeri Hendrickx
                            Aug 27 '10 at 8:16






                          • 3





                            @JoeriHendrickx If the programmer is adding hours to a date, then very likely they are doing other date-time work. I don’t consider Joda-Time unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new java.time.* package (inspired by Joda-Time) to Java 8.

                            – Basil Bourque
                            Feb 17 '14 at 6:14











                          • I had trouble with Joda on android. Kept getting ClassNotDefinedException

                            – TheRealChx101
                            Nov 8 '15 at 17:39













                          23














                          23










                          23









                          With Joda-Time



                          DateTime dt = new DateTime();
                          DateTime added = dt.plusHours(6);





                          share|improve this answer















                          With Joda-Time



                          DateTime dt = new DateTime();
                          DateTime added = dt.plusHours(6);






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Feb 17 '14 at 6:14









                          Basil Bourque

                          135k38 gold badges448 silver badges635 bronze badges




                          135k38 gold badges448 silver badges635 bronze badges










                          answered Aug 27 '10 at 5:18









                          BabarBabar

                          1,9182 gold badges20 silver badges32 bronze badges




                          1,9182 gold badges20 silver badges32 bronze badges










                          • 2





                            +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library

                            – Joeri Hendrickx
                            Aug 27 '10 at 8:16






                          • 3





                            @JoeriHendrickx If the programmer is adding hours to a date, then very likely they are doing other date-time work. I don’t consider Joda-Time unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new java.time.* package (inspired by Joda-Time) to Java 8.

                            – Basil Bourque
                            Feb 17 '14 at 6:14











                          • I had trouble with Joda on android. Kept getting ClassNotDefinedException

                            – TheRealChx101
                            Nov 8 '15 at 17:39












                          • 2





                            +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library

                            – Joeri Hendrickx
                            Aug 27 '10 at 8:16






                          • 3





                            @JoeriHendrickx If the programmer is adding hours to a date, then very likely they are doing other date-time work. I don’t consider Joda-Time unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new java.time.* package (inspired by Joda-Time) to Java 8.

                            – Basil Bourque
                            Feb 17 '14 at 6:14











                          • I had trouble with Joda on android. Kept getting ClassNotDefinedException

                            – TheRealChx101
                            Nov 8 '15 at 17:39







                          2




                          2





                          +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library

                          – Joeri Hendrickx
                          Aug 27 '10 at 8:16





                          +1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library

                          – Joeri Hendrickx
                          Aug 27 '10 at 8:16




                          3




                          3





                          @JoeriHendrickx If the programmer is adding hours to a date, then very likely they are doing other date-time work. I don’t consider Joda-Time unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new java.time.* package (inspired by Joda-Time) to Java 8.

                          – Basil Bourque
                          Feb 17 '14 at 6:14





                          @JoeriHendrickx If the programmer is adding hours to a date, then very likely they are doing other date-time work. I don’t consider Joda-Time unnecessary at all; the first thing I do when setting up any new project is add Joda-Time. Even Sun and Oracle agreed that the old java.util.Date & Calendar need to be phased out, so they added the new java.time.* package (inspired by Joda-Time) to Java 8.

                          – Basil Bourque
                          Feb 17 '14 at 6:14













                          I had trouble with Joda on android. Kept getting ClassNotDefinedException

                          – TheRealChx101
                          Nov 8 '15 at 17:39





                          I had trouble with Joda on android. Kept getting ClassNotDefinedException

                          – TheRealChx101
                          Nov 8 '15 at 17:39











                          22
















                          Since Java 8:



                          LocalDateTime.now().minusHours(1);


                          See LocalDateTime API.






                          share|improve this answer






















                          • 4





                            Close but not quite right. You should go for a ZonedDateTime rather than a LocalDateTime. The "Local" means not tied to any particular locality, and not tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See my Answer by comparison.

                            – Basil Bourque
                            Oct 8 '15 at 16:37






                          • 1





                            Also to get a java.util.Date object as requester had asked us ZonedDateTime.toInstant() and Date.from() as described here stackoverflow.com/a/32274725/5661065

                            – hayduke
                            Oct 18 '17 at 0:28















                          22
















                          Since Java 8:



                          LocalDateTime.now().minusHours(1);


                          See LocalDateTime API.






                          share|improve this answer






















                          • 4





                            Close but not quite right. You should go for a ZonedDateTime rather than a LocalDateTime. The "Local" means not tied to any particular locality, and not tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See my Answer by comparison.

                            – Basil Bourque
                            Oct 8 '15 at 16:37






                          • 1





                            Also to get a java.util.Date object as requester had asked us ZonedDateTime.toInstant() and Date.from() as described here stackoverflow.com/a/32274725/5661065

                            – hayduke
                            Oct 18 '17 at 0:28













                          22














                          22










                          22









                          Since Java 8:



                          LocalDateTime.now().minusHours(1);


                          See LocalDateTime API.






                          share|improve this answer















                          Since Java 8:



                          LocalDateTime.now().minusHours(1);


                          See LocalDateTime API.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Sep 23 '15 at 2:02

























                          answered Feb 12 '14 at 23:48









                          leventovleventov

                          9,1234 gold badges44 silver badges80 bronze badges




                          9,1234 gold badges44 silver badges80 bronze badges










                          • 4





                            Close but not quite right. You should go for a ZonedDateTime rather than a LocalDateTime. The "Local" means not tied to any particular locality, and not tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See my Answer by comparison.

                            – Basil Bourque
                            Oct 8 '15 at 16:37






                          • 1





                            Also to get a java.util.Date object as requester had asked us ZonedDateTime.toInstant() and Date.from() as described here stackoverflow.com/a/32274725/5661065

                            – hayduke
                            Oct 18 '17 at 0:28












                          • 4





                            Close but not quite right. You should go for a ZonedDateTime rather than a LocalDateTime. The "Local" means not tied to any particular locality, and not tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See my Answer by comparison.

                            – Basil Bourque
                            Oct 8 '15 at 16:37






                          • 1





                            Also to get a java.util.Date object as requester had asked us ZonedDateTime.toInstant() and Date.from() as described here stackoverflow.com/a/32274725/5661065

                            – hayduke
                            Oct 18 '17 at 0:28







                          4




                          4





                          Close but not quite right. You should go for a ZonedDateTime rather than a LocalDateTime. The "Local" means not tied to any particular locality, and not tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See my Answer by comparison.

                          – Basil Bourque
                          Oct 8 '15 at 16:37





                          Close but not quite right. You should go for a ZonedDateTime rather than a LocalDateTime. The "Local" means not tied to any particular locality, and not tied to the timeline. Like "Christmas starts at midnight on December 25, 2015" is a different moment across the various time zones, with no meaning until you apply a particular time zone to get a particular moment on the time line. Furthermore, without a time zone Daylight Saving Time (DST) and other anomalies will not be handled with such use of LocalDateTime. See my Answer by comparison.

                          – Basil Bourque
                          Oct 8 '15 at 16:37




                          1




                          1





                          Also to get a java.util.Date object as requester had asked us ZonedDateTime.toInstant() and Date.from() as described here stackoverflow.com/a/32274725/5661065

                          – hayduke
                          Oct 18 '17 at 0:28





                          Also to get a java.util.Date object as requester had asked us ZonedDateTime.toInstant() and Date.from() as described here stackoverflow.com/a/32274725/5661065

                          – hayduke
                          Oct 18 '17 at 0:28











                          14
















                          Something like:



                          Date oldDate = new Date(); // oldDate == current time
                          final long hoursInMillis = 60L * 60L * 1000L;
                          Date newDate = new Date(oldDate().getTime() +
                          (2L * hoursInMillis)); // Adds 2 hours





                          share|improve this answer




















                          • 1





                            FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

                            – Basil Bourque
                            Mar 25 '18 at 18:48















                          14
















                          Something like:



                          Date oldDate = new Date(); // oldDate == current time
                          final long hoursInMillis = 60L * 60L * 1000L;
                          Date newDate = new Date(oldDate().getTime() +
                          (2L * hoursInMillis)); // Adds 2 hours





                          share|improve this answer




















                          • 1





                            FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

                            – Basil Bourque
                            Mar 25 '18 at 18:48













                          14














                          14










                          14









                          Something like:



                          Date oldDate = new Date(); // oldDate == current time
                          final long hoursInMillis = 60L * 60L * 1000L;
                          Date newDate = new Date(oldDate().getTime() +
                          (2L * hoursInMillis)); // Adds 2 hours





                          share|improve this answer













                          Something like:



                          Date oldDate = new Date(); // oldDate == current time
                          final long hoursInMillis = 60L * 60L * 1000L;
                          Date newDate = new Date(oldDate().getTime() +
                          (2L * hoursInMillis)); // Adds 2 hours






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Aug 27 '10 at 5:46









                          Christopher HuntChristopher Hunt

                          1,7441 gold badge13 silver badges19 bronze badges




                          1,7441 gold badge13 silver badges19 bronze badges










                          • 1





                            FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

                            – Basil Bourque
                            Mar 25 '18 at 18:48












                          • 1





                            FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

                            – Basil Bourque
                            Mar 25 '18 at 18:48







                          1




                          1





                          FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

                          – Basil Bourque
                          Mar 25 '18 at 18:48





                          FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

                          – Basil Bourque
                          Mar 25 '18 at 18:48











                          14
















                          Using the newish java.util.concurrent.TimeUnit class you can do it like this



                           Date oldDate = new Date(); // oldDate == current time
                          Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Adds 2 hours





                          share|improve this answer





























                            14
















                            Using the newish java.util.concurrent.TimeUnit class you can do it like this



                             Date oldDate = new Date(); // oldDate == current time
                            Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Adds 2 hours





                            share|improve this answer



























                              14














                              14










                              14









                              Using the newish java.util.concurrent.TimeUnit class you can do it like this



                               Date oldDate = new Date(); // oldDate == current time
                              Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Adds 2 hours





                              share|improve this answer













                              Using the newish java.util.concurrent.TimeUnit class you can do it like this



                               Date oldDate = new Date(); // oldDate == current time
                              Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Adds 2 hours






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Oct 15 '13 at 23:41









                              IainIain

                              3774 silver badges10 bronze badges




                              3774 silver badges10 bronze badges
























                                  6
















                                  This is another piece of code when your Date object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.



                                   String myString = "09:00 12/12/2014";
                                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
                                  Date myDateTime = null;

                                  //Parse your string to SimpleDateFormat
                                  try

                                  myDateTime = simpleDateFormat.parse(myString);

                                  catch (ParseException e)

                                  e.printStackTrace();

                                  System.out.println("This is the Actual Date:"+myDateTime);
                                  Calendar cal = new GregorianCalendar();
                                  cal.setTime(myDateTime);

                                  //Adding 21 Hours to your Date
                                  cal.add(Calendar.HOUR_OF_DAY, 21);
                                  System.out.println("This is Hours Added Date:"+cal.getTime());


                                  Here is the Output:



                                   This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
                                  This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014





                                  share|improve this answer

























                                  • You could also use: Calendar cal = Calendar.getInstance();

                                    – Stefan Sprenger
                                    Aug 21 '15 at 8:35















                                  6
















                                  This is another piece of code when your Date object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.



                                   String myString = "09:00 12/12/2014";
                                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
                                  Date myDateTime = null;

                                  //Parse your string to SimpleDateFormat
                                  try

                                  myDateTime = simpleDateFormat.parse(myString);

                                  catch (ParseException e)

                                  e.printStackTrace();

                                  System.out.println("This is the Actual Date:"+myDateTime);
                                  Calendar cal = new GregorianCalendar();
                                  cal.setTime(myDateTime);

                                  //Adding 21 Hours to your Date
                                  cal.add(Calendar.HOUR_OF_DAY, 21);
                                  System.out.println("This is Hours Added Date:"+cal.getTime());


                                  Here is the Output:



                                   This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
                                  This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014





                                  share|improve this answer

























                                  • You could also use: Calendar cal = Calendar.getInstance();

                                    – Stefan Sprenger
                                    Aug 21 '15 at 8:35













                                  6














                                  6










                                  6









                                  This is another piece of code when your Date object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.



                                   String myString = "09:00 12/12/2014";
                                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
                                  Date myDateTime = null;

                                  //Parse your string to SimpleDateFormat
                                  try

                                  myDateTime = simpleDateFormat.parse(myString);

                                  catch (ParseException e)

                                  e.printStackTrace();

                                  System.out.println("This is the Actual Date:"+myDateTime);
                                  Calendar cal = new GregorianCalendar();
                                  cal.setTime(myDateTime);

                                  //Adding 21 Hours to your Date
                                  cal.add(Calendar.HOUR_OF_DAY, 21);
                                  System.out.println("This is Hours Added Date:"+cal.getTime());


                                  Here is the Output:



                                   This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
                                  This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014





                                  share|improve this answer













                                  This is another piece of code when your Date object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.



                                   String myString = "09:00 12/12/2014";
                                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
                                  Date myDateTime = null;

                                  //Parse your string to SimpleDateFormat
                                  try

                                  myDateTime = simpleDateFormat.parse(myString);

                                  catch (ParseException e)

                                  e.printStackTrace();

                                  System.out.println("This is the Actual Date:"+myDateTime);
                                  Calendar cal = new GregorianCalendar();
                                  cal.setTime(myDateTime);

                                  //Adding 21 Hours to your Date
                                  cal.add(Calendar.HOUR_OF_DAY, 21);
                                  System.out.println("This is Hours Added Date:"+cal.getTime());


                                  Here is the Output:



                                   This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
                                  This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Dec 15 '14 at 0:01









                                  vkramsvkrams

                                  3,47414 gold badges55 silver badges92 bronze badges




                                  3,47414 gold badges55 silver badges92 bronze badges















                                  • You could also use: Calendar cal = Calendar.getInstance();

                                    – Stefan Sprenger
                                    Aug 21 '15 at 8:35

















                                  • You could also use: Calendar cal = Calendar.getInstance();

                                    – Stefan Sprenger
                                    Aug 21 '15 at 8:35
















                                  You could also use: Calendar cal = Calendar.getInstance();

                                  – Stefan Sprenger
                                  Aug 21 '15 at 8:35





                                  You could also use: Calendar cal = Calendar.getInstance();

                                  – Stefan Sprenger
                                  Aug 21 '15 at 8:35











                                  4
















                                  If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:



                                  import java.time.Duration;
                                  import java.time.LocalDateTime;

                                  ...

                                  LocalDateTime yourDate = ...

                                  ...

                                  // Adds 1 hour to your date.

                                  yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
                                  // OR
                                  yourDate = yourDate + Duration.parse("PT1H"); // Groovy.





                                  share|improve this answer






















                                  • 1





                                    Duration.parse(iso8601duration) is interesting, thanks, but you cannot use operator + on LocalDateTime, you might want to edit that. But .plus(...) does work.

                                    – qlown
                                    May 24 '17 at 22:42












                                  • Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly.

                                    – Daniel
                                    May 24 '17 at 22:49











                                  • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                    – Basil Bourque
                                    Mar 28 at 22:11











                                  • @BasilBourque Date object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out LocalDateTime for ZonedDateTime.

                                    – Daniel
                                    Mar 28 at 23:12
















                                  4
















                                  If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:



                                  import java.time.Duration;
                                  import java.time.LocalDateTime;

                                  ...

                                  LocalDateTime yourDate = ...

                                  ...

                                  // Adds 1 hour to your date.

                                  yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
                                  // OR
                                  yourDate = yourDate + Duration.parse("PT1H"); // Groovy.





                                  share|improve this answer






















                                  • 1





                                    Duration.parse(iso8601duration) is interesting, thanks, but you cannot use operator + on LocalDateTime, you might want to edit that. But .plus(...) does work.

                                    – qlown
                                    May 24 '17 at 22:42












                                  • Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly.

                                    – Daniel
                                    May 24 '17 at 22:49











                                  • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                    – Basil Bourque
                                    Mar 28 at 22:11











                                  • @BasilBourque Date object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out LocalDateTime for ZonedDateTime.

                                    – Daniel
                                    Mar 28 at 23:12














                                  4














                                  4










                                  4









                                  If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:



                                  import java.time.Duration;
                                  import java.time.LocalDateTime;

                                  ...

                                  LocalDateTime yourDate = ...

                                  ...

                                  // Adds 1 hour to your date.

                                  yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
                                  // OR
                                  yourDate = yourDate + Duration.parse("PT1H"); // Groovy.





                                  share|improve this answer















                                  If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:



                                  import java.time.Duration;
                                  import java.time.LocalDateTime;

                                  ...

                                  LocalDateTime yourDate = ...

                                  ...

                                  // Adds 1 hour to your date.

                                  yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
                                  // OR
                                  yourDate = yourDate + Duration.parse("PT1H"); // Groovy.






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited May 24 '17 at 22:50

























                                  answered May 24 '17 at 22:21









                                  DanielDaniel

                                  3,2442 gold badges31 silver badges57 bronze badges




                                  3,2442 gold badges31 silver badges57 bronze badges










                                  • 1





                                    Duration.parse(iso8601duration) is interesting, thanks, but you cannot use operator + on LocalDateTime, you might want to edit that. But .plus(...) does work.

                                    – qlown
                                    May 24 '17 at 22:42












                                  • Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly.

                                    – Daniel
                                    May 24 '17 at 22:49











                                  • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                    – Basil Bourque
                                    Mar 28 at 22:11











                                  • @BasilBourque Date object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out LocalDateTime for ZonedDateTime.

                                    – Daniel
                                    Mar 28 at 23:12













                                  • 1





                                    Duration.parse(iso8601duration) is interesting, thanks, but you cannot use operator + on LocalDateTime, you might want to edit that. But .plus(...) does work.

                                    – qlown
                                    May 24 '17 at 22:42












                                  • Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly.

                                    – Daniel
                                    May 24 '17 at 22:49











                                  • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                    – Basil Bourque
                                    Mar 28 at 22:11











                                  • @BasilBourque Date object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out LocalDateTime for ZonedDateTime.

                                    – Daniel
                                    Mar 28 at 23:12








                                  1




                                  1





                                  Duration.parse(iso8601duration) is interesting, thanks, but you cannot use operator + on LocalDateTime, you might want to edit that. But .plus(...) does work.

                                  – qlown
                                  May 24 '17 at 22:42






                                  Duration.parse(iso8601duration) is interesting, thanks, but you cannot use operator + on LocalDateTime, you might want to edit that. But .plus(...) does work.

                                  – qlown
                                  May 24 '17 at 22:42














                                  Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly.

                                  – Daniel
                                  May 24 '17 at 22:49





                                  Thanks @qlown, I guess the + is working in groovy because that's how I'm using it now. I'll modify the answer accordingly.

                                  – Daniel
                                  May 24 '17 at 22:49













                                  The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                  – Basil Bourque
                                  Mar 28 at 22:11





                                  The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                  – Basil Bourque
                                  Mar 28 at 22:11













                                  @BasilBourque Date object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out LocalDateTime for ZonedDateTime.

                                  – Daniel
                                  Mar 28 at 23:12






                                  @BasilBourque Date object is deprecated. The question is ambiguous when it comes to the time zone so my answers stands. Furthermore, you can just swap out LocalDateTime for ZonedDateTime.

                                  – Daniel
                                  Mar 28 at 23:12












                                  4
















                                  You can do it with Joda DateTime API



                                  DateTime date= new DateTime(dateObj);
                                  date = date.plusHours(1);
                                  dateObj = date.toDate();





                                  share|improve this answer



























                                  • Working after I changed the 1st line into DateTime dateTime= new DateTime(dateObj);

                                    – Sundararaj Govindasamy
                                    Jun 7 '17 at 19:49















                                  4
















                                  You can do it with Joda DateTime API



                                  DateTime date= new DateTime(dateObj);
                                  date = date.plusHours(1);
                                  dateObj = date.toDate();





                                  share|improve this answer



























                                  • Working after I changed the 1st line into DateTime dateTime= new DateTime(dateObj);

                                    – Sundararaj Govindasamy
                                    Jun 7 '17 at 19:49













                                  4














                                  4










                                  4









                                  You can do it with Joda DateTime API



                                  DateTime date= new DateTime(dateObj);
                                  date = date.plusHours(1);
                                  dateObj = date.toDate();





                                  share|improve this answer















                                  You can do it with Joda DateTime API



                                  DateTime date= new DateTime(dateObj);
                                  date = date.plusHours(1);
                                  dateObj = date.toDate();






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Aug 10 '17 at 5:24

























                                  answered Dec 7 '16 at 7:28









                                  RaTRaT

                                  4442 gold badges7 silver badges23 bronze badges




                                  4442 gold badges7 silver badges23 bronze badges















                                  • Working after I changed the 1st line into DateTime dateTime= new DateTime(dateObj);

                                    – Sundararaj Govindasamy
                                    Jun 7 '17 at 19:49

















                                  • Working after I changed the 1st line into DateTime dateTime= new DateTime(dateObj);

                                    – Sundararaj Govindasamy
                                    Jun 7 '17 at 19:49
















                                  Working after I changed the 1st line into DateTime dateTime= new DateTime(dateObj);

                                  – Sundararaj Govindasamy
                                  Jun 7 '17 at 19:49





                                  Working after I changed the 1st line into DateTime dateTime= new DateTime(dateObj);

                                  – Sundararaj Govindasamy
                                  Jun 7 '17 at 19:49











                                  3
















                                  Date argDate = new Date(); //set your date.
                                  String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
                                  SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
                                  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
                                  String dateTime = sdf.format(argDate) + " " + argTime;
                                  Date requiredDate = dateFormat.parse(dateTime);





                                  share|improve this answer





























                                    3
















                                    Date argDate = new Date(); //set your date.
                                    String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
                                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
                                    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
                                    String dateTime = sdf.format(argDate) + " " + argTime;
                                    Date requiredDate = dateFormat.parse(dateTime);





                                    share|improve this answer



























                                      3














                                      3










                                      3









                                      Date argDate = new Date(); //set your date.
                                      String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
                                      SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
                                      SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
                                      String dateTime = sdf.format(argDate) + " " + argTime;
                                      Date requiredDate = dateFormat.parse(dateTime);





                                      share|improve this answer













                                      Date argDate = new Date(); //set your date.
                                      String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
                                      SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
                                      SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
                                      String dateTime = sdf.format(argDate) + " " + argTime;
                                      Date requiredDate = dateFormat.parse(dateTime);






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Oct 8 '15 at 11:47









                                      Ghost RiderGhost Rider

                                      791 silver badge7 bronze badges




                                      791 silver badge7 bronze badges
























                                          0
















                                          by using Java 8 classes. we can manipulate date and time very easily as below.



                                          LocalDateTime today = LocalDateTime.now();
                                          LocalDateTime minusHours = today.minusHours(24);
                                          LocalDateTime minusMinutes = minusHours.minusMinutes(30);
                                          LocalDate localDate = LocalDate.from(minusMinutes);





                                          share|improve this answer

























                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:08
















                                          0
















                                          by using Java 8 classes. we can manipulate date and time very easily as below.



                                          LocalDateTime today = LocalDateTime.now();
                                          LocalDateTime minusHours = today.minusHours(24);
                                          LocalDateTime minusMinutes = minusHours.minusMinutes(30);
                                          LocalDate localDate = LocalDate.from(minusMinutes);





                                          share|improve this answer

























                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:08














                                          0














                                          0










                                          0









                                          by using Java 8 classes. we can manipulate date and time very easily as below.



                                          LocalDateTime today = LocalDateTime.now();
                                          LocalDateTime minusHours = today.minusHours(24);
                                          LocalDateTime minusMinutes = minusHours.minusMinutes(30);
                                          LocalDate localDate = LocalDate.from(minusMinutes);





                                          share|improve this answer













                                          by using Java 8 classes. we can manipulate date and time very easily as below.



                                          LocalDateTime today = LocalDateTime.now();
                                          LocalDateTime minusHours = today.minusHours(24);
                                          LocalDateTime minusMinutes = minusHours.minusMinutes(30);
                                          LocalDate localDate = LocalDate.from(minusMinutes);






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Mar 25 '18 at 18:10









                                          Abdul GafoorAbdul Gafoor

                                          5845 silver badges10 bronze badges




                                          5845 silver badges10 bronze badges















                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:08


















                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:08

















                                          The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                          – Basil Bourque
                                          Mar 28 at 22:08






                                          The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                          – Basil Bourque
                                          Mar 28 at 22:08












                                          0
















                                          You can use the LocalDateTime class from Java 8. For eg :



                                          long n = 4;
                                          LocalDateTime localDateTime = LocalDateTime.now();
                                          System.out.println(localDateTime.plusHours(n));





                                          share|improve this answer

























                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:10















                                          0
















                                          You can use the LocalDateTime class from Java 8. For eg :



                                          long n = 4;
                                          LocalDateTime localDateTime = LocalDateTime.now();
                                          System.out.println(localDateTime.plusHours(n));





                                          share|improve this answer

























                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:10













                                          0














                                          0










                                          0









                                          You can use the LocalDateTime class from Java 8. For eg :



                                          long n = 4;
                                          LocalDateTime localDateTime = LocalDateTime.now();
                                          System.out.println(localDateTime.plusHours(n));





                                          share|improve this answer













                                          You can use the LocalDateTime class from Java 8. For eg :



                                          long n = 4;
                                          LocalDateTime localDateTime = LocalDateTime.now();
                                          System.out.println(localDateTime.plusHours(n));






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Mar 25 '18 at 18:21









                                          Sajit GuptaSajit Gupta

                                          701 silver badge5 bronze badges




                                          701 silver badge5 bronze badges















                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:10

















                                          • The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                            – Basil Bourque
                                            Mar 28 at 22:10
















                                          The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                          – Basil Bourque
                                          Mar 28 at 22:10





                                          The Question is about a Date object, which represent a specific moment in UTC. Your use of LocalDateTime fails to address the Question. LocalDateTime lacks any concept of time zone or offset-from-UTC, and therefore cannot represent a moment. Wrong class for this problem. See What's the difference between Instant and LocalDateTime?

                                          – Basil Bourque
                                          Mar 28 at 22:10











                                          -1
















                                          You can use this method, It is easy to understand and implement :



                                          public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) 
                                          Calendar calendar = Calendar.getInstance();
                                          calendar.setTime(date);
                                          calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
                                          calendar.add(Calendar.MINUTE, nombreMinute);
                                          calendar.add(Calendar.SECOND, nombreSeconde);
                                          return calendar.getTime();






                                          share|improve this answer

























                                          • This approach is already presented in another Answer posted years ago. I do not see how this one adds anymore value.

                                            – Basil Bourque
                                            Jan 13 '17 at 17:37












                                          • The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :)

                                            – Nimpo
                                            Jan 15 '17 at 12:12















                                          -1
















                                          You can use this method, It is easy to understand and implement :



                                          public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) 
                                          Calendar calendar = Calendar.getInstance();
                                          calendar.setTime(date);
                                          calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
                                          calendar.add(Calendar.MINUTE, nombreMinute);
                                          calendar.add(Calendar.SECOND, nombreSeconde);
                                          return calendar.getTime();






                                          share|improve this answer

























                                          • This approach is already presented in another Answer posted years ago. I do not see how this one adds anymore value.

                                            – Basil Bourque
                                            Jan 13 '17 at 17:37












                                          • The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :)

                                            – Nimpo
                                            Jan 15 '17 at 12:12













                                          -1














                                          -1










                                          -1









                                          You can use this method, It is easy to understand and implement :



                                          public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) 
                                          Calendar calendar = Calendar.getInstance();
                                          calendar.setTime(date);
                                          calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
                                          calendar.add(Calendar.MINUTE, nombreMinute);
                                          calendar.add(Calendar.SECOND, nombreSeconde);
                                          return calendar.getTime();






                                          share|improve this answer













                                          You can use this method, It is easy to understand and implement :



                                          public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) 
                                          Calendar calendar = Calendar.getInstance();
                                          calendar.setTime(date);
                                          calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
                                          calendar.add(Calendar.MINUTE, nombreMinute);
                                          calendar.add(Calendar.SECOND, nombreSeconde);
                                          return calendar.getTime();







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jan 13 '17 at 17:01









                                          NimpoNimpo

                                          1441 silver badge9 bronze badges




                                          1441 silver badge9 bronze badges















                                          • This approach is already presented in another Answer posted years ago. I do not see how this one adds anymore value.

                                            – Basil Bourque
                                            Jan 13 '17 at 17:37












                                          • The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :)

                                            – Nimpo
                                            Jan 15 '17 at 12:12

















                                          • This approach is already presented in another Answer posted years ago. I do not see how this one adds anymore value.

                                            – Basil Bourque
                                            Jan 13 '17 at 17:37












                                          • The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :)

                                            – Nimpo
                                            Jan 15 '17 at 12:12
















                                          This approach is already presented in another Answer posted years ago. I do not see how this one adds anymore value.

                                          – Basil Bourque
                                          Jan 13 '17 at 17:37






                                          This approach is already presented in another Answer posted years ago. I do not see how this one adds anymore value.

                                          – Basil Bourque
                                          Jan 13 '17 at 17:37














                                          The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :)

                                          – Nimpo
                                          Jan 15 '17 at 12:12





                                          The added value of my proposal is simplicity and ease of implementation, the user just has to paste it and use it and add the hours, minutes or seconds, as you know, the level of Beginners differs and if the proposed answers combines between simple answers and advanced answers it will be appreciable :)

                                          – Nimpo
                                          Jan 15 '17 at 12:12


















                                          draft saved

                                          draft discarded















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3581258%2fadding-n-hours-to-a-date-in-java%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해