get China Time - Android Internationalization

Android examples for Internationalization:Chinese

Description

get China Time

Demo Code


//package com.java2s;

import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Date;

public class Main {
    /**//w  w  w  .  j a va  2  s .com
     * depends on baidu open api
     * 
     * @return
     */
    public static Date getChinaTime() {
        Date date = null;
        String target = null;

        try {
            final String url = "http://open.baidu.com/special/time/";
            final String enc = "UTF-8";
            final String ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";

            HttpURLConnection connection = (HttpURLConnection) (new URL(url)
                    .openConnection());
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("User-Agent", ua);
            connection.setRequestProperty("Charset", enc);
            connection.setConnectTimeout(2 * 1000);
            connection.setReadTimeout(2 * 1000);
            InputStream inputStream = connection.getInputStream();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, enc), 512);

            target = reader.readLine();
            while (null != target) {
                target = reader.readLine();

                if (target.contains("window.baidu_time(")) {
                    int start = target.lastIndexOf("(");
                    int end = target.lastIndexOf(")");

                    if (start > 0 && end > 0 && end > start) {
                        target = target.substring(start + 1, end);
                        break;
                    }
                }
            }

            reader.close();

        } catch (Exception e) {
            // [Neo] Empty
        }

        try {
            long timestamp = Long.parseLong(target);
            date = new Date(timestamp);
        } catch (Exception e) {
        }

        return date;
    }
}

Related Tutorials