0

I have a TextView that store a getDate() value. This getDate() value is a date but the format is String

 textview_device_datetime.setText(data.getDate().replace('T', ' '));

this is the result

16-08-2015 16:15:16

but i would add 2 hours to this String Date. How can i do?

Any help is great. Thanks

dev_
  • 395
  • 1
  • 3
  • 16
  • 3
    Covert the string to a `Date` object by parsing the string and then add 2 hours to it. Again convert back to the string. There are plenty of questions which can help you do the above steps :) – Shobhit Puri Aug 17 '15 at 17:45
  • Glad to see you wanting to participate in StackOverflow. But please **search before posting**. Your question about adding hours to a date-time (and secondarily parsing/generating strings from date-time values) has been handled [many times already](http://stackoverflow.com/search?q=java+date+add+hours). – Basil Bourque Aug 17 '15 at 21:02

2 Answers2

9
final String dateString = "16-08-2015 16:15:16";
final long millisToAdd = 7_200_000; //two hours

DateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

Date d = format.parse(dateString);
d.setTime(d.getTime() + millisToAdd);

System.out.println("New value: " + d); //New value: Sun Aug 16 18:15:16 CEST 2015
Emile Pels
  • 3,837
  • 1
  • 15
  • 23
1

Here I have attached the code for it with example.

import java.time.*;
import java.text.*;
import java.util.*;
public class AddTime
{
  public static void main(String[] args)
  {
    String myTime = "16-08-2015 16:15:16";
    System.out.println(addHour(myTime,2));
  }

  public static String addHour(String myTime,int number)
  {
    try
    {
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    Date d = df.parse(myTime); 
    Calendar cal = Calendar.getInstance();
    cal.setTime(d);
    cal.add(Calendar.HOUR, number);
    String newTime = df.format(cal.getTime());
    return newTime;  
    } 
    catch(ParseException e)
    {
      System.out.println(" Parsing Exception");
    }
    return null;

  }
}