【问题标题】:Adding/Subtracting 5 seconds from Java Date - Showing deprected warning从 Java 日期添加/减去 5 秒 - 显示不推荐使用的警告
【发布时间】:2022-02-03 17:53:17
【问题描述】:

我想在当前时间上增加 5 秒

    Date date = new Date();

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

它会生成我需要的正确输出:

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

但它给了我一个警告错误消息

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

这是什么意思。忽略此警告是否安全?如果不是那怎么处理呢?

【问题讨论】:

标签: java datetime


【解决方案1】:

你可以使用date.setTime(date.getTime() + 5000)

【讨论】:

    【解决方案2】:

    你可以试试这个。日历是您正在寻找的最佳解决方案。

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

    输出:

    Thu Apr 17 14:53:20 IST 2014
    

    【讨论】:

      【解决方案3】:

      deprecated 表示不应再使用此方法,因为它可以从 Java 语言中移除以支持其他方法(它可能不会被移除,但它不再是更可取的做事方式) . Documentation 建议您使用 Calendar.get(Calendar.SECOND),这是您应该在代码中使用的内容。

      请注意,从 Java 8 开始,您可以再次使用 LocalDateTime#getSecond 方法。

      【讨论】:

      • Andy 建议 date.setTime(date.getTime() + 5000) 并且它可以在没有警告消息的情况下工作。实际上我想使用 Date 对象。可以使用date.setTime(date.getTime() + 5000) 代替转到日历对象吗?
      • 在这个简单的例子中是这样,但是在一些更高级的日期算术的情况下,可能需要使用Calendar 类。
      • 另外,通过使用Calendar,您的代码将更具可读性,因为您不会在日期中添加一些神奇的数字,而是明确说明要添加的内容。
      • 实际上我需要通过yyyy-MM-dd'T'HH:mm:ss将日期以xml日期时间格式存储在XML文件中。我目前正在执行SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 如何为calendar 执行此操作。除了 xml 格式,我还需要对日期进行日期比较操作。 Calendar 仍然是我的最佳选择吗?
      • a)您可以通过Calendar#getTime() 以同样的方式进行操作。 b)mkyong.com/java/how-to-compare-dates-in-java
      【解决方案4】:

      Java 8 具有完全不同的 time-api 并使处理日期更加容易。 Here's an article

      使用 Java 版本 5-7(恕我直言,不应使用以下所有内容)您应该使用日历 (as Petr suggested) 如果你被允许使用第三方 API,你一定要看看JodaTime

      【讨论】:

        【解决方案5】:

        显示已弃用的警告意味着 java中有一些更好的方法可以做到这一点。

        【讨论】:

          【解决方案6】:

          java.time

          建议该页面的未来访问者使用 java.time API。 java.util 的日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,转用modern date-time API

          当地时间:

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

          本地日期和时间:

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

          带有时区的日期和时间:

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

          时间线上的瞬时点:

          java.time.Instant 模拟时间线上的单个瞬时点并且独立于时区。它是最常用的函数,toEpochMilliofEpochMilli 用于将时刻转换为从 1970-01-01T00:00:00Z 开始的毫秒数,以及从 1970-01-01T00 开始的毫秒数: 00:00Z 分别到瞬间。注意Z代表Zulu,代表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);
              }
          }
          

          Trail: Date Time 了解有关现代日期时间 API 的更多信息。

          乔达时间

          摘自Home Page of Joda-Time

          Joda-Time 是 Java 的事实上的标准日期和时间库 在 Java SE 8 之前。现在要求用户迁移到 java.time (JSR-310)。

          当地时间:

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

          本地日期和时间:

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

          带有时区的日期和时间:

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

          时间线上的瞬时点:

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

          旧版 API:

          java.util.Date 对象不像modern date-time types 那样是真正的日期时间对象;相反,它表示距离Epoch of January 1, 1970 的毫秒数。当你打印一个java.util.Date 的对象时,它的toString 方法返回从这个毫秒值计算的日期时间。由于java.util.Date 没有时区信息,它会应用您的JVM 的时区并显示相同的信息。如果您需要在不同的时区打印日期时间,则需要将时区设置为SimpleDateFomrat 并从中获取格式化字符串。

          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 作为传统 API 和现代 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);
              }
          }
          

          无论出于何种目的,如果您想将instant 转换为java.util.Date 的对象:

          Date dateTime = Date.from(instant);
          

          【讨论】:

            【解决方案7】:

            仅供参考,这里是一些使用Joda-Time 2.3 的示例代码。捆绑的 java.util.Date 和 .Calendar 类是出了名的麻烦,应该避免。

            与 java.util.Date 不同,Joda-Time DateTime 对象具有指定的时区。

            指定时区时,请使用proper time zone name。避免使用三四个字母代码,因为它们既不标准化也不唯一。

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

            转储到控制台...

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

            运行时……

            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
            

            【讨论】:

              【解决方案8】:

              一个简单的方法是使用 apache DateUtils

              import org.apache.commons.lang.time.DateUtils;
              
              DateUtils.addSeconds(now, 5); // Add 5 seconds.
              DateUtils.addSeconds(now, -5); // Subtracting 5 seconds
              

              您还可以添加/减去分钟、小时等...

              【讨论】:

                【解决方案9】:

                最简单的解决方案:

                如果是当前日期,请使用:

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

                特定日期:

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

                同样,你可以通过这个技巧增加或减少任何时间。

                【讨论】:

                  猜你喜欢
                  • 2020-01-31
                  • 2020-03-15
                  • 2020-05-14
                  • 1970-01-01
                  • 2010-12-23
                  • 2014-07-24
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多