adesh singh
adesh singh

Reputation: 1727

How to add some time in the system time?

I am trying to get the system date by using the following code . Now i want after adding 123 minutes it should automatically add 2 in hours and three in minutes how is it possible? I am using the following code.

      try{ 

     SimpleDateFormat  sdf = new SimpleDateFormat("HH:mm:ss");
       Date  date = new Date();
       String s = sdf.format(date);
       }

      catch(Exception ex)
       {
       ex.printStackTrace();
       }

Upvotes: 1

Views: 171

Answers (4)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

This will work

    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    Date date = new Date();
    System.out.println(df.format(date));
    long milSec=date.getTime();
    long addMilSec=123*60*1000;

    long sum=milSec+addMilSec;
    Date d=new Date(sum);

    System.out.println(df.format(d));

Upvotes: 0

Michael Shrestha
Michael Shrestha

Reputation: 2555

try like this

 Calendar now = Calendar.getInstance();
 now.setTime(YOUR_DATE_OBJECT);//pass your date here

 now.add(Calendar.MINUTE, 50);//add 5o minutes
 now.add(Calendar.SECOND, -50);// subtract 50 seconds

Upvotes: 0

morgano
morgano

Reputation: 17422

Create a GregorianCalendar object: http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html add you hours/minutes/whatever you need to add and then get back a Date

Upvotes: 1

Cephalopod
Cephalopod

Reputation: 15145

Create a Calendar object, instead of Date, and use add.

Example:

Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 123);
String s = sdf.format(c.getTime());

Upvotes: 0

Related Questions