简体   繁体   中英

real-time date from server on java?

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

     

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM