Adding/Subtracting 5 seconds from Java Date - Showing deprected warning

后端 未结 8 844
旧巷少年郎
旧巷少年郎 2021-01-23 01:43

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);         


        
相关标签:
8条回答
  • 2021-01-23 02:12

    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

    0 讨论(0)
  • 2021-01-23 02:12

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

    0 讨论(0)
  • 2021-01-23 02:13

    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.

    • For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
    • If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

    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);
    
    0 讨论(0)
  • 2021-01-23 02:25

    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 讨论(0)
  • 2021-01-23 02:26

    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.

    0 讨论(0)
  • 2021-01-23 02:27

    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
    
    0 讨论(0)
提交回复
热议问题