java—从api/json中提取时间并将其与设置的日期进行比较

2fjabf4q  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(282)
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()
  }
}

如何将calendar now-dateutils.getatomictime()更改为这个新api
我的问题:我不知道如何使用我必须检查的时间和参考它。
喜欢它正确地打印时间,但是现在我如何使用printlnjsontostring,然后使用它将它添加到上面的代码中,以比较我设置的过期日期和api日期。
请给我一些建议。谢谢您。

icnyk63a

icnyk63a1#

巴兹尔布尔克的答案指引你走向正确的方向。这个答案集中在你应该写什么代码上。
全班同学, Instant 充当传统日期时间api和现代日期时间api之间的桥梁。转换 java.util.Calendar 对象(从中获取 json.get("date") )至 Instant 使用 Calendar#toInstant .
对于到期日期,可以创建 Instant 对象使用 OffsetDateTime 对象集 ZoneOffset.UTC .
最后,您可以比较 Instant 使用 Instant#isAfter .
根据上面给出的解释,您需要编写以下代码:

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。
注意,api的日期时间 java.util 以及它们的格式化api, SimpleDateFormat 过时且容易出错。建议完全停止使用它们,并切换到现代日期时间api。
出于任何原因,如果您必须坚持使用Java6或Java7,您可以使用threeten backport,它将大部分java.time功能向后移植到Java6和Java7。
如果您正在为一个android项目工作,并且您的android api级别仍然不符合java-8,请检查通过desugaring提供的java8+api以及如何在android项目中使用threetenabp。

lztngnrs

lztngnrs2#

热释光;博士

你的问题不清楚。但您似乎想比较从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类所取代。
将epoch秒转换为 Instant 通过呼叫 Instant.ofEpochSecond . 通过a 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() ;

所有这些已经在堆栈溢出上讨论过很多次了。搜索以了解更多信息。

3pmvbmvn

3pmvbmvn3#

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

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

相关问题