Java Examples - URL Connection Date


Advertisements


Problem Description

How to get the date of URL connection ?

Solution

Following example demonstrates how to get the date of URL connection by using httpurlcon.getDate() method of HttpURLConnection class.

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main {
   public static void main(String args[]) throws Exception {
      URL url = new URL("http://www.google.com");
      HttpURLConnection httpurlcon = (HttpURLConnection) url.openConnection();
      long date = httpurlcon.getDate();
      
      if (date == 0)System.out.println("No date information.");
      else System.out.println("Date: " + new Date(date));
   }
}

Result

The above code sample will produce the following result.

Date:05.26.2009

The following is an example to get the date of URL connection.

import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class NewClass {
   public static void main(String args[]) throws Exception { 
      URL url = new URL("http://www.tutorialspoint.com");
      HttpURLConnection httpurlcon = (HttpURLConnection) url.openConnection();
      long date = httpurlcon.getDate();
      Long dateTime = httpurlcon.getLastModified();
      
      httpurlcon.disconnect();
      ZonedDateTime urlLastModified;
      urlLastModified = ZonedDateTime.ofInstant(
         Instant.ofEpochMilli(dateTime), ZoneId.of("GMT"));
      
      if (date == 0) {
         System.out.println("No date information.");
      } else {
         System.out.println("Date: " + new Date(date));
      }
   }
}
Date: Wed Nov 23 11:11:23 IST 2016

java_networking.htm

Advertisements