将 GMT 时间更改为当地时间

发布于 2025-01-12 09:00:36 字数 1840 浏览 1 评论 0原文

我想要一个时间应用程序,它从 Google 获取当前时间,然后将其转换为当地时间。

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

现在,如果我在不同的国家/地区,它应该相应地显示当前时间。有人可以帮忙吗?我尝试使用 VPN,但它仍然显示每个国家/地区的相同时间。谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

第七度阳光i 2025-01-19 09:00:36

tl;dr

使用现代的 java.time 类。

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

您正在使用可怕的日期时间类,这些类多年前已被 JSR 310 中定义的现代 java.time 类取代。切勿使用日期日历SimpleDateFormat等。

将您的输入字符串解析为 ZonedDateTime。无需指定格式模式。 DateTimeFormatter 类与符合 RFC 1123 / RFC 822 标准的输入字符串的预定义格式化程序捆绑在一起。

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

调整到您想要的时区。

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

或者使用 JVM 当前的默认时区。

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

生成文本。我建议自动本地化。

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

完整的示例代码

这是一个完整的类,作为示例。

在此示例中,我们使用 Java 11+ 中内置的 HTTP 客户端实现。请参阅JEP 321:HTTP 客户端。警告:我是这个框架的新手。我只写了最少的内容以使示例正常工作。不要将此视为使用这些 HTTP 类的有根据的建议。

我们有一个 GoogleTime 类,其中包含一对名为 now 的公共静态方法。两者都返回从 Google 网站获取的日期时间字符串,调整为时区并本地化为区域设置。一种 now 方法使用 JVM 当前的默认时区和区域设置,而在另一种方法中,您可以指定区域和区域。语言环境。

这项工作被分成一对私有方法。 On 方法从 Google.com 站点获取。另一种方法将标头字符串解析为 ZonedDateTime 对象,调整到另一个时区,并生成表示调整时刻的值的文本。

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

用法。

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

运行时。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文