【问题标题】:Convert Date.toString() back to Date in Java [duplicate]在 Java 中将 Date.toString() 转换回 Date [重复]
【发布时间】:2015-05-07 15:17:00
【问题描述】:

我正在调用一个 API,根据指南,每次调用它都是低效的,因为数据不会定期更改。他们建议调用一次,然后在 10 分钟后才进行轮询。

我从一个 Android 应用程序调用它,所以我想存储当前日期加上 10 分钟。我是这样做的:

Date forecastRefreshDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(forecastRefreshDate);
cal.add(Calendar.MINUTE, 10);
editor.putString("ForecastRefreshDate", forecastRefreshDate.toString());
editor.apply();

因此,现在再次运行此代码时,它需要检查当前时间(new Date())是否 > 保存在缓存/应用文件中的值。

如何创建一个 Date 变量,该变量等于作为字符串存储在缓存中的值?

【问题讨论】:

  • 可能是因为这个问题可以通过一些研究轻松回答。您可以找到 String Date.toString() 返回的格式并查看解析结果。

标签: java android


【解决方案1】:

将日期转换为纪元时间,这是存储为 long 的毫秒数。将 long 存储为字符串并在需要时解析回 long。

long epoch = date.getTime(); //where date is your Date
String yourString = Long.toString(epoch); //to string for storage
long time = Long.valueOf(yourString).longValue(); ; //back to epoch
Date originaldate = new Date(Long.parseLong(time)); //back to date

【讨论】:

    【解决方案2】:

    在处理时间时,仅在内部需要它来衡量时间段, 最好将时间戳存储为长值(毫秒 1.1.1970 UTC)。

    使用long timestamp = System.currentTimeMillis()

    如果需要 String 存储,只需将 Long 转换为 String。

    String timeStampStr = String.parseLong(timeStamp);
    

    不要将 Date.toString 用于记录或调试以外的其他事情。 toString() 表示在其他国家/地区可能不同。 如果需要人类可读的时间戳字符串,您必须指定特定的DateFormat,另请参阅DateFormatter。

    【讨论】:

      【解决方案3】:

      解析 long 它是最有效的方式,但可能存在您已经将日期格式化为其他格式并想要解析它的情况。那么你应该使用这个

      private static final String format = "yyyy-MM-dd HH:mm:ss";
      private static final SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
      private Calendar dateTime = Calendar.getInstance();
      
      public void setDateTime(String dateTimeString) {
          try {
              dateTime.setTime(formatter.parse(dateTimeString));
          } catch (ParseException e) {
               // Dummy handled exception
              dateTime.setTimeInMillis(0);
          }
      }
      

      解析一个包含自纪元以来的毫秒数的 long

      Date date = new Date(Long.parseLong(timeInMillisecondsString));
      

      【讨论】:

        【解决方案4】:

        由于您使用的是普通的toString(),它应该可以使用SimpleDateFormat 覆盖。

        试试这个:

        DateFormat dateFormat = new SimpleDateFormat();
        Date myDate = dateFormat.parse(myDateString);
        

        【讨论】:

          猜你喜欢
          • 2012-03-14
          • 2017-03-24
          • 1970-01-01
          • 2011-11-21
          • 1970-01-01
          • 2015-11-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多