【发布时间】: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,您需要点击答案左侧的大勾号(✓)。