0
System.out.println(json.toString());
System.out.println(json.get("date"));

returns time in epoch time such as: 1609642292

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

This is what I'm using to pull the date from the 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"));
    }
}

In my other java file I'm trying to do something like

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()
  }
}

How can I change Calendar now - DateUtils.getatomicTime() to this new API

My problems: I don't know how to use what I have to check for the time and refer to it.

Like it prints the time properly, but now how do I use that println jsontostring and then use that to add it to that code slightly above to compare my Set Expiration Date with API date.

Please give me some advice. Thank you.

3 Answers3

0

It appears that the goal is to use the epoch time in the date element of the server response and call shutdown if that is earlier than the current time. Instead of creating Calendar instances, I would compare the current epoch time to the value in the HTTP response.

    if (DateUtils.readJsonFromUrl("https://Time.xyz/api/date").get("date") * 1000 < System.currentTimeMillis()) {
        shutdown();
    } else {
        startProgram();
    }
John
  • 1,322
  • 14
  • 26
  • Yes close! Goal is to use the epoch time in the date element of the server response and call ```shutdown``` IF it is AFTER the set expiry date. This is just my tiny, simple way of making my software stop working after X amount of days. I'll try to implement your method and see if it works for me. Thank you. – MeApeSmallBrain Jan 03 '21 at 05:28
  • In what way is this answer lacking? There doesn't appear to be any call for Calendar since the goal is only to find out whether the current time is later than the expiry time included in the server response. – John Jan 08 '21 at 14:24
0

tl;dr

Your Question is not clear. But it seems you want to compare some moment represented as a textual number of whole seconds since 1970-01-01T00:00Z to some number of calendar days past the current moment as captured from a remote time server using some library you’ve not explained.

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`.
;

Details

Never use Calendar. That terrible class was supplanted years ago by the modern java.time classes.

Convert your epoch seconds to Instant by calling Instant.ofEpochSecond. Pass a long parsed from your textual input.

Apparently a call to the DateUtils.getAtomicTime, of some library you neglected to mention, results in Java.until.Date. Convert that terrible legacy class to its modern replacement, java.time.Instant. Notice the new to… and from… conversion methods added to the old legacy classes.

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

Compare to current moment.

boolean isInTheFuture = someInstant.isAfter( now ) ;

You commented about “x amount of days”. Did you mean calendars days or generic chunks of 24-hours? If the latter:

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

If you meant calendar days, apply a time zone.

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

All of this has been covered many many many times already on Stack Overflow. Search to learn more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Hi, thank you for the response, and yes I've been told to stop using the depreciated Calendar class, just haven't gotten around to it. I meant the former, calendar days. I did plan on using Instant.now() but that uses the system clock which someone can easily adjust, so I'm using a set date that I code in. This doesn't really address my main question: using that Jsontostring function in that code above and using the printed epoch date to compare with my set date. If Epoch date(from API) is greater than Set Date -> shutdown(). Need help making that comparison. – MeApeSmallBrain Jan 03 '21 at 05:59
  • I showed you comparisons: `isBefore` and `isAfter` on `Instant`. Again, all this has been covered many times. Search Stack Overflow thoroughly before posting. – Basil Bourque Jan 03 '21 at 06:01
0

The answer by Basil Bourque guides you in the right direction. This answer is focused on what code you should write.

The class, Instant serves as the bridge between the legacy date-time API and the modern date-time API. Convert the java.util.Calendar object (which you are getting from json.get("date")) to Instant using Calendar#toInstant.

For expiry date, you can create an Instant object using the OffsetDateTime object set with ZoneOffset.UTC.

Finally, you can compare these two objects of Instant using Instant#isAfter.

Based on the explanation given above, you need to write the following code:

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();
}

Learn about the modern date-time API from Trail: Date Time.

Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110