Home > front end >  real-time date from server on java?
real-time date from server on java?

Time:04-23

how to take the real-time date and time from the server where my jar is deployed on java?

I want to set the creation date of my orders to the date-time when the server received the request, how can I do that in java?

I tried:

  Date newDate = new Date();
  Date createdDate = DATE_FORMATTER_SERVER.parse(DATE_FORMATTER_SERVER.format(newDate));

     

CodePudding user response:

Try the following and adapt it to your needs:

 Date remoteDate = null;
 URL url = new URL(REMOTE_SERVER_URL);
 URLConnection urlConnection = url.openConnection();
 HttpURLConnection connection = (HttpURLConnection) urlConnection;
 connection.setConnectTimeout(10000);
 connection.setReadTimeout(10000);
 connection.setInstanceFollowRedirects( true );
 connection.setRequestProperty( "User-agent", "spider" );
 connection.connect();
 
 Map<String,List<String>> header = connection.getHeaderFields();
 for (String key : header.keySet()) {
     if (key != null && "Date".equals(key)) {
         List<String> data = header.get(key);
         String dateString = data.get(0);
         SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
         remoteDate = sdf.parse(dateString);
         break;
     }
 }

CodePudding user response:

tl;dr

java.time.Instant.now().toString() 

Details

Never use Date and SimpleDateFormat. These legacy classes are terribly flawed in design. They were years ago supplanted by the modern java.time classes defined in JSR 310.

Capture the current moment as seen in UTC, an offset of zero hours-minutes-seconds.

Instant instant = Instant.now() ;

Serialize to text using standard format from ISO 8601.

String output = instant.toString() ;

Parse such strings.

Instant instant = Instant.parse( input ) ;
  • Related