【问题标题】:Pulling time from api/json and comparing it to a set date从 api/json 中提取时间并将其与设定的日期进行比较
【发布时间】:2021-01-03 04:50:01
【问题描述】:
System.out.println(json.toString());
System.out.println(json.get("date"));

以纪元时间返回时间,例如:1609642292

> Task :Program:DateUtils.main()
{"date":1609642292}
1609642292

这是我用来从 API 中提取日期的方法


import java.io.InputStreamReader;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;
public class DateUtils
{
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
//        InputStream is = new URL(url).openStream();
        try (var is = new URL(url).openStream()) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        }
    }
    public static void main(String[] args) throws IOException, JSONException {
        JSONObject json = readJsonFromUrl("https://Time.xyz/api/date"); //Don't want to post real API
        System.out.println(json.toString());
        System.out.println(json.get("date"));
    }
}

在我的其他 java 文件中,我正在尝试做类似的事情

Calendar expiry = Calendar.getInstance();
expiry.set(2021,1,31,0,0) //When my program expires:year, month, date, hour, min
Calendar now = DateUtils.getAtomicTime(); 
  //where DateUtils.getAtomicTime comes from this class that pulls current time from the National Institute of Standards and Technology
  //https://www.rgagnon.com/javadetails/java-0589.html
if (now.after(expiry)) {
      shutdown()
}else{
     startProgram()
  }
}

我该如何改变 现在日历 - DateUtils.getatomicTime() 到这个新 API

我的问题: 不知道怎么用,得查时间,参考一下。

喜欢它正确地打印时间,但是现在我如何使用该 println jsontostring,然后使用它来将其添加到略高于上面的代码中,以比较我的 Set Expiration Date 和 API 日期。

请给我一些建议。谢谢。

【问题讨论】:

  • 提供DateUtils.getAtomicTime的库的名称和链接。
  • MeApeSmallBrain - 如果其中一个答案解决了您的问题,您可以通过将其标记为已接受来帮助社区。接受的答案有助于未来的访问者自信地使用该解决方案。要mark an answer as accepted,您需要点击答案左侧的大勾号(✓)。

标签: java json api time


【解决方案1】:

目标似乎是在服务器响应的date 元素中使用纪元时间,如果该时间早于当前时间,则调用shutdown。 我不会创建日历实例,而是将当前纪元时间与 HTTP 响应中的值进行比较。

    if (DateUtils.readJsonFromUrl("https://Time.xyz/api/date").get("date") * 1000 < System.currentTimeMillis()) {
        shutdown();
    } else {
        startProgram();
    }

【讨论】:

  • 是的,关闭!目标是在服务器响应的日期元素中使用纪元时间,并在设置的到期日期之后调用shutdown。这只是我让我的软件在 X 天后停止工作的微小而简单的方法。我会尝试实现你的方法,看看它是否适合我。谢谢。
  • 这个答案缺少什么?似乎没有任何对日历的调用,因为目标只是找出当前时间是否晚于服务器响应中包含的到期时间。
【解决方案2】:

tl;博士

您的问题不清楚。但是您似乎想将表示为自 1970-01-01T00:00Z 以来的整秒文本数的某个时刻与使用您尚未解释的某个库从远程时间服务器捕获的当前时刻过去的某些日历天数进行比较.

boolean isFurtherOutIntoTheFuture = 
    Instant                              // Represent a moment, a point on the timeline, resolving to nanoseconds, as seen in UTC.
    .ofEpochSecond(                      // Interpret a number as a count of whole seconds since the epoch reference point of 1970-01-01T00:00Z.
        Long.parseLong( "1609642292" )   // Parse text as a number, a 64-bit `long`.
    )                                    // Returns a `Instant`.
    .isAfter(                            // Compare one `Instant` object to another.
        DateUtils                        // Some mysterious library that fetches current moment from a remote time server. 
        .getAtomicTime()                 // Returns a `java.until.Date` object (apparently – not explained in Question).
        .toInstant()                     // Convert from legacy class to its modern replacement.
        .atZone(                         // Adjust from UTC to some time zone. Same moment, different wall-clock time. 
            ZoneId.of( "Africa/Tunis" )  // Whatever time zone by which you want to add some number of calendar days.
        )                                // Returns a `ZonedDateTime` object.
        .plusDays( x )                   // Add some number of calendar days (*not* necessarily 24-hours long). Returns a new `ZonedDateTime` object with values based on the original. 
        .toInstant()                     // Adjust from some time zone to UTC (an offset-from-UTC of zero hours, minutes, and seconds).
    )                                    // Returns a `boolean`.
;

详情

永远不要使用Calendar。那个可怕的类在几年前被现代的 java.time 类所取代。

通过调用Instant.ofEpochSecond 将您的纪元秒数转换为Instant。传递从您的文本输入中解析的long

显然调用 DateUtils.getAtomicTime,您忽略了提到的某个库,结果是 Java.until.Date。将那个可怕的遗留类转换为现代替代品java.time.Instant。请注意添加到旧遗留类中的新 to…from… 转换方法。

Instant now = DateUtils.getAtomicTime().toInstant() ;

与当前时刻比较。

boolean isInTheFuture = someInstant.isAfter( now ) ;

您评论了“x 天”。您是指日历天还是 24 小时的通用块?如果是后者:

Instant later = myInstant.plus( Duration.ofDays( x ) ) ;

如果您指的是日历日,请应用时区。

ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
ZonedDateTime later = zdt.plusDays( x ) ;
Instant laterInUtc = later.toInstant() ;

所有这些都已经在 Stack Overflow 上进行了很多次介绍。搜索以了解更多信息。

【讨论】:

  • 您好,感谢您的回复,是的,有人告诉我停止使用已折旧的 Calendar 类,只是还没开始使用它。我的意思是前一个日历日。我确实计划使用 Instant.now() 但它使用了有人可以轻松调整的系统时钟,所以我使用的是我编码的设定日期。这并没有真正解决我的主要问题:使用该 Jsontostring 函数上面的代码并使用打印的纪元日期与我设定的日期进行比较。如果 Epoch 日期(来自 API)大于 Set Date -> shutdown()。需要帮助进行比较。
  • 我向你展示了比较:Instant 上的isBeforeisAfter。同样,所有这些都已被多次介绍。在发布之前彻底搜索 Stack Overflow。
【解决方案3】:

Basil Bourque 的回答将引导您朝着正确的方向前进。这个答案的重点是你应该写什么代码。

Instant 类充当了传统日期时间 API 和现代日期时间 API 之间的桥梁。使用Calendar#toInstantjava.util.Calendar 对象(您从json.get("date") 获取)转换为Instant

对于到期日期,您可以使用带有ZoneOffset.UTCOffsetDateTime 对象集创建Instant 对象。

最后,您可以使用Instant#isAfter 比较Instant 的这两个对象。

根据上面给出的解释,需要编写如下代码:

JSONObject json = readJsonFromUrl("https://Time.xyz/api/date");
Calendar now = json.get("date");
Instant instantNow = now.toInstant();
Instant expiry = OffsetDateTime.of(LocalDateTime.of(2021, 1, 31, 0, 0), ZoneOffset.UTC).toInstant();
if (instantNow.isAfter(expiry)) {
    shutdown();
} else {
    startProgram();
}

Trail: Date Time 了解现代日期时间 API。

请注意,java.util 的日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议彻底停止使用,转用modern date-time API

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    相关资源
    最近更新 更多