'Change GMT Time to Local Time

I want a Time App that gets the current time from Google and then converts it to Local Time.

  private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            OkHttpClient httpclient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://google.com/")
                    .build();

            try (okhttp3.Response response = httpclient
                    .newCall(request)
                    .execute()) {

                String currentDateTime = response.header("Date").toString().replace("Date: ", "");
                if (currentDateTime.contains("GMT")) {
                    Date date = null;
                    SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zz");
                    try {
                        date = formatter.parse(currentDateTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Current Date  :" + currentDateTime);
                    System.out.println("Converted Date  :" + date+"");

                    SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                    GoogleDate = sd.format(date);
                    System.out.println("Google Date  :" + GoogleDate);

                } else {
                   // GoogleDateCall();
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            }

            return GoogleDate;
        }

        @Override
        protected void onPostExecute(String serverDate) {

            displayTime.setText(serverDate);
        }
    }

Now if I am in a different country it should display the current time accordingly. Can anyone help? I tried to use VPN but still, it always show me the same time for every country. Thank you



Solution 1:[1]

tl;dr

Use the modern java.time classes.

ZonedDateTime.parse( 
    input , 
    DateTimeFormatter.RFC_1123_DATE_TIME  // Your text complies with this obsolescent standard format.
)
.withZoneSameInstant(
    ZoneId.systemDefault() ;  // Or, specify a time zone.
)
.format(
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.MEDIUM )  // Specify length versus abbreviation.
    .withLocale( Locale.getDefault() )  // Or, specify a locale.
)

java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date, Calendar, SimpleDateFormat, and so on.

Parse your input string as a ZonedDateTime. No need to specify a formatting pattern. Thé DateTimeFormatter class comes bundled with a predefined formatter for your input string that complies with the RFC 1123 / RFC 822 standards.

ZonedDateTime zdt = ZonedDateTime.parse( input , DateTimeFormatter.RFC_1123_DATE_TIME ) ;

Adjust to your desired time zone.

ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdtEdmonton = zdt.withZoneSameInstant( z ) ;

Or use the JVM’s current default time zone.

ZonedDateTime zdtDefault = zdt.withZoneSameInstant( ZoneId.systemDefault() ) ;

Generate text. I suggest automatically localizing.

Locale locale = Locale.CANADA_FRENCH ;  // Or Locale.US etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale ) ;
String output = zdtEdmonton.format( f ) ;

Complete example code

Here is a full class, as an example.

In this example, we use the HTTP client implementation built into Java 11+. See JEP 321: HTTP Client. Caveat: I am a newbie with this framework. I wrote bare minimum to get example working. Do not take this as well-founded advice on using these HTTP classes.

We have a single GoogleTime class with a pair of public static methods named now. Both return a string of the date-time obtained from the Google site, adjusted into a time zone, and localized to a locale. One now method uses the JVM’s current default time zone and locale, while in the other you may specify zone & locale.

The work is split into a pair of private methods. On method fetches from the Google.com site. The other method parses the header string into a ZonedDateTime object, adjusts into another time zone, and generates text representing the value of the adjusted moment.

package work.basil.googletime;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class GoogleTime
{
    public static String now ( ZoneId zoneId , Locale locale , FormatStyle formatStyle )
    {
        GoogleTime googleTime = new GoogleTime();
        String dateHeader = googleTime.fetchDateHeader();
        if ( dateHeader.isBlank() ) { return ""; }
        return googleTime.parseAdjustAndFormat( dateHeader , zoneId , locale , formatStyle );
    }

    public static String now ( )
    {
        return GoogleTime.now( ZoneId.systemDefault() , Locale.getDefault() , FormatStyle.MEDIUM );
    }

    private String fetchDateHeader ( )
    {
        String url = "https://google.com/";

        final HttpClient httpClient =
                HttpClient.newBuilder()
                        .version( HttpClient.Version.HTTP_1_1 )
                        .connectTimeout( Duration.ofSeconds( 10 ) )
                        .build();

        final HttpRequest request =
                HttpRequest.newBuilder()
                        .GET()
                        .uri( URI.create( url ) )
                        .setHeader( "User-Agent" , "Java 11 HttpClient Bot" ) // add request header
                        .build();

        final HttpResponse < String > response;
        try { response = httpClient.send( request , HttpResponse.BodyHandlers.ofString() ); } catch ( IOException | InterruptedException e ) { return ""; }

        // Examine response headers.
        HttpHeaders headers = response.headers();
        // headers.map().forEach( ( k , v ) -> System.out.println( k + " ? " + v ) );
        List < String > dateHeaderList = headers.map().get( "date" );
        if ( Objects.isNull( dateHeaderList ) ) { return ""; }
        if ( dateHeaderList.size() == 0 ) { return ""; }
        return dateHeaderList.get( 0 );
    }

    private String parseAdjustAndFormat ( String input , ZoneId zoneId , Locale locale , FormatStyle formatStyle )
    {
        // Parse.
        ZonedDateTime zdtParsed;
        try { zdtParsed = ZonedDateTime.parse( input , DateTimeFormatter.RFC_1123_DATE_TIME ); } catch ( DateTimeException e ) { return ""; }
        // Adjust.
        ZonedDateTime zdtAdjusted = zdtParsed.withZoneSameInstant( zoneId );
        // Format.
        DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( formatStyle ).withLocale( locale );
        String output = zdtAdjusted.format( f );
        return output;
    }
}

Usage.

System.out.println( GoogleTime.now() );
System.out.println( GoogleTime.now( ZoneId.of( "Europe/Rome" ) , Locale.ITALY , FormatStyle.SHORT ) );

When run.

Mar 5, 2022, 11:17:57 PM
06/03/22, 08:17

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1