【问题标题】:What is the alternative for getMonthValue(),getDayOfMonth() in java 7?java 7 中 getMonthValue(),getDayOfMonth() 的替代方法是什么?
【发布时间】:2022-02-11 05:46:28
【问题描述】:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS");
Date date = new Date();

如何使这个 Java 7 兼容?我应该做些什么改变?

String part = date.getYear() + "" + String.format("%02d", date.getMonthValue()) + ""
        + String.format("%02d", date.getDayOfMonth()) + "" + String.format("%02d", date.getHour()) + ""
        + String.format("%02d", date.getMinute()) + "" + String.format("%02d", date.getSecond());

【问题讨论】:

  • 不确定你在问什么,但 public int getMonth() 已弃用。从 JDK 1.1 版开始,由 Calendar.get(Calendar.MONTH) 取代。
  • 你可以在 Java 7 中使用Joda Time

标签: java string date simpledateformat


【解决方案1】:

可怕的 DateCalendarSimpleDateFormat 类已被 JSR 310 中定义并内置到 Java 8+ 中的现代 java.time 类所取代。

无需将输出字符串拼凑在一起。请改用DateTimeFormatter 对象。

ZonedDateTime zdt = ZonedDateTime.now() ;
String output = 
    zdt
    .truncatedTo( ChronoUnit.SECONDS )
    .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;

对于 Java 6 和 7,将 java.time 的后端端口添加到您的项目 ThreeTen-Backport 库中。该 API 几乎与 java.time 相同,因此稍后将您的项目升级到现代 Java 只需更改 import 语句即可。

如您所知,Java 6 and 7 are years past their end-of-life。如果可能,我建议您考虑迁移到 Java 8、11 或 17。

【讨论】:

    【解决方案2】:

    如果无法升级 Java(从版本 7)并避免使用任何外部库,请使用 SimpleDateFormat

    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = new Date();
    String part = dateFormat.format(date);
    

    可以根据需要更改模式:参见SimpleDateFormat 类的documentation

    正如 this answer 中已经建议的那样,升级到更新的 Java,然后使用 java.time 包和子包中的类(如 DateTimeFormatter)。

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 2014-01-16
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多