-2

I have a date array. I want to add 20 seconds to each of the elements in the array. I tried

     for(int i=0i<20;i++)
     {
      date1[i]=date1[i].gettime()+20;
     }

This gives a long int value. But what i need is time format result.My question is it possible to add seconds using built in functions or manual function should be written for the same.

Keerthana
  • 157
  • 4
  • 18
  • Please add more context to your question. It is unclear what you hope to accomplish. – crush Jan 29 '14 at 17:20
  • @crush : I have no idea of how to add..so just tried that method..Googled a lot ..found that in php it can be strtotime() converts it and then we add seconds to it..I dont know about java..thats y asking – Keerthana Jan 29 '14 at 17:21
  • You have a [`Date`](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html) object. You want to add 20 (seconds?) to it, then output it in some type of `string` format. Is that right? – crush Jan 29 '14 at 17:23
  • I'd recommend using [`Calendar`](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) instead of `Date`. Is that an option? – crush Jan 29 '14 at 17:25
  • possible duplicate of [How to add 30 minutes to a javascript Date object?](http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object) – showdev Jan 29 '14 at 20:44

2 Answers2

1

That is because Date.getTime() returns number of milliseconds since January 1, 1970, 00:00:00 GMT. So you are resetting the value in your array with Long. To convert it back to Date you need to construct new Date object like this.

 for(int i = 0; i < 20; i++) {
  date1[i] = new Date(date1[i].gettime() + TimeUnit.SECONDS.toMillis(20));
 }

or set the time back like this:

 for(int i = 0; i < 20; i++) {
  date1[i].setTime(date1[i].gettime() + TimeUnit.SECONDS.toMillis(20));
 }

But I would strongly advice you to use Joda Time instead of Java Date API

klor
  • 3,596
  • 2
  • 13
  • 13
0

The getTime() methond return the time in milliseconds. Add 20000 to that and then create date based on those milliseconds. The java doc tells you how to convert milliseconds to date.

ruben056
  • 112
  • 8