5

I want to add 5 seconds to current time

    Date date = new Date();

    date.setSeconds(date.getSeconds()+ 5);
    System.out.println("old Value is: "+date);
    System.out.println("New Value is: "+ date);

It generates the correct output exactly what I needed as:

Old Value is: Thu Apr 17 14:10:33 PKT 2014
New Value is: Thu Apr 17 14:10:38 PKT 2014

but it gives me a warning error message as

Multiple markers at this line
    - The method getSeconds() from the type Date is deprecated
    - The method setSeconds(int) from the type Date is 
     deprecated

What this means. Is it safe to ignore this warning? if not then how to handle it?

1

9 Answers 9

9

you can use date.setTime(date.getTime() + 5000)

4

You can try this. Calendar is the best solution you are looking at.

Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                             .parse("2014-04-17 14:53:25");
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.SECOND,(calendar.get(Calendar.SECOND)-5));

System.out.println(calendar.getTime());

Out put:

Thu Apr 17 14:53:20 IST 2014
3

deprecated means that this method should't be used anymore because it can be removed from the Java language in favor of some other method (it probably won't be removed but it's not the preferable way of doing things anymore). Documentation suggests you to use Calendar.get(Calendar.SECOND) which is what you should use in your code.

Note that from Java 8 you can use LocalDateTime#getSecond method again.

5
  • Andy suggested date.setTime(date.getTime() + 5000) and it works with no warning messages. Actually I want to work with Date object. Is it ok to use date.setTime(date.getTime() + 5000) instead for going to Calendar object ? Apr 17, 2014 at 9:28
  • In this simple case it is, however in case of some more advanced date arithmetic it might be necessary to use Calendar class. Apr 17, 2014 at 9:30
  • Also by using Calendar you will get your code more readable because you are not adding some magical numbers to your date but you explicitly say what is being added to what. Apr 17, 2014 at 9:31
  • Actually I will need to store the date in XML file in xml datetime format by yyyy-MM-dd'T'HH:mm:ss. Which I am currently performing SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); How to do this for calendar. And beside xml format, I will also need date comparison operations on date. Does the Calendar is still best option for me? Apr 17, 2014 at 9:52
  • a)You can do it the same way via Calendar#getTime(). b) mkyong.com/java/how-to-compare-dates-in-java Apr 17, 2014 at 14:35
3

Java 8 has completly different time-api and makes handling dates a lot easier. Here's an article

With Java Versions 5-7 (everything below should not be used IMHO) you should use Calendar (as Petr suggested) If you are allowed to use third-party APIs, you should definitly take a look at JodaTime

2

showing deprecated warning that means there is some better way available in java to do so.

0
1

java.time

The future visitors of this page are recommended to use java.time API. The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

Just local time:

import java.time.LocalTime;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        // ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
        // requirement e.g. to ZoneId.of("Europe/London")
        LocalTime localTimeNow = LocalTime.now(ZoneId.systemDefault());
        System.out.println(localTimeNow);

        // After 5 seconds
        LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
        System.out.println(localTimeAfter5Sec);
    }
}

Local date & time:

import java.time.LocalDateTime;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        // ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
        // requirement e.g. to ZoneId.of("Europe/London")
        LocalDateTime ldtNow = LocalDateTime.now(ZoneId.systemDefault());
        System.out.println(ldtNow);

        // After 5 seconds
        LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
        System.out.println(ldtAfter5Sec);
    }
}

Date & time with timezone:

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        // ZoneId.systemDefault() returns the time-zone of JVM. Change it as per your
        // requirement e.g. to ZoneId.of("Europe/London")
        ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.systemDefault());
        System.out.println(zdtNow);

        // After 5 seconds
        ZonedDateTime zdtAfter5Sec = zdtNow.plusSeconds(5);
        System.out.println(zdtAfter5Sec);
    }
}

An instantaneous point on the time-line:

java.time.Instant models a single instantaneous point on the time-line and is independent of timezone. It's most commonly used functions, toEpochMilli and ofEpochMilli are used to convert an instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z, and milliseconds from the epoch of 1970-01-01T00:00:00Z to an instant respectively. Note that Z stands for Zulu and represents UTC+00:00.

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        // This moment
        Instant now = Instant.now();
        System.out.println(now);

        // Moment after 5 sec
        Instant momentAfter5Sec = now.plusSeconds(5);
        System.out.println(momentAfter5Sec);
    }
}

Learn more about the modern date-time API from Trail: Date Time.

Joda-time

An excerpt from the Home Page of Joda-Time

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Just local time:

import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        // DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
        // requirement e.g. to DateTimeZone.forID("Europe/London")
        LocalTime localTimeNow = LocalTime.now(DateTimeZone.getDefault());
        System.out.println(localTimeNow);

        // After 5 seconds
        LocalTime localTimeAfter5Sec = localTimeNow.plusSeconds(5);
        System.out.println(localTimeAfter5Sec);
    }
}

Local date & time:

import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        // DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
        // requirement e.g. to DateTimeZone.forID("Europe/London")
        LocalDateTime ldtNow = LocalDateTime.now(DateTimeZone.getDefault());
        System.out.println(ldtNow);

        // After 5 seconds
        LocalDateTime ldtAfter5Sec = ldtNow.plusSeconds(5);
        System.out.println(ldtAfter5Sec);
    }
}

Date & time with timezone:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class Main {
    public static void main(String[] args) {
        // DateTimeZone.getDefault() returns the time-zone of JVM. Change it as per your
        // requirement e.g. to DateTimeZone.forID("Europe/London")
        DateTime dtNow = new DateTime(DateTimeZone.getDefault());
        System.out.println(dtNow);

        // After 5 seconds
        DateTime dtAfter5Sec = dtNow.plusSeconds(5);
        System.out.println(dtAfter5Sec);
    }
}

An instantaneous point on the time-line:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class Main {
    public static void main(String[] args) {
        DateTime now = new DateTime(DateTimeZone.UTC);
        System.out.println(now);

        // After 5 seconds
        DateTime after5Sec = now.plusSeconds(5);
        System.out.println(after5Sec);
    }
}

Legacy API:

The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getTime());

        calendar.add(Calendar.SECOND, 5);// -5 if you want to subtract
        System.out.println(calendar.getTime());
    }
}

java.time.Instant as the bridge between the legacy and the modern API:

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        Instant instant = date.toInstant();

        // Now you can convert instant to other types of java.time e.g.
        ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Dubai"));
        System.out.println(zdt);
    }
}

For whatsoever purpose, if you want to convert instant to an object of java.util.Date:

Date dateTime = Date.from(instant);
1

Easiest solution:

if it is the current date use:

Long seconds= 10; //update in seconds 

//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(System.currentTimeMillis() - (seconds*1000) );

For a specific Date:

Long seconds= 10;   //update in seconds
//seconds*1000 to convert second to millisecond
Date dateAfterUpdation = new Date(oldDate.getTime() - (seconds*1000) ); 

Similarly, you can add or subtract any amount of time by this trick.

0

FYI, here is some example code using Joda-Time 2.3. The bundled java.util.Date and .Calendar classes are notoriously troublesome, and should be avoided.

Unlike a java.util.Date, a Joda-Time DateTime object has an assigned time zone.

When specifying time zones, use a proper time zone name. Avoid the three or four letter codes as they are neither standardized nor unique.

java.util.Date date = new java.util.Date(); // Has no time zone. Misnamed, as it contains both a date and a time portions.

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Karachi" );
DateTime dateTime = new DateTime( date, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
DateTime fiveSecondsAgo = dateTime.minusSeconds( 5 );
java.util.Date date2 = fiveSecondsAgo.toDate();

Dump to console…

System.out.println( "date: " + date );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "fiveSecondsAgo: " + fiveSecondsAgo );
System.out.println( "date2: " + date2 );

When run…

date: Thu Apr 17 14:44:01 PDT 2014
dateTime: 2014-04-18T02:44:01.773+05:00
dateTimeUtc: 2014-04-17T21:44:01.773Z
fiveSecondsAgo: 2014-04-18T02:43:56.773+05:00
date2: Thu Apr 17 14:43:56 PDT 2014
0

An easy way is to use apache DateUtils.

import org.apache.commons.lang.time.DateUtils;

DateUtils.addSeconds(now, 5); // Add 5 seconds.
DateUtils.addSeconds(now, -5); // Subtracting 5 seconds

You can also add/subtract minutes, hours, and so on...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.