Android Code Snippet Getting date time from the internet

The local date time of phone or handheld device would be easily affected by user setting.
In order to get the accurate date time, we can make use of the http header requested from any stable website!

In Chrome, pressing F12 and refreshing, we can see the date from the response.
g6b5rx5.png


By using library OkHttp, OkHttpClient instance works together with OkHttpRequest instance to get the http header:
http request and response:
Sub sendHeaderRequest()
    Dim hc As OkHttpClient
    hc.Initialize("hc")
    Dim req As OkHttpRequest
    strUrl = m_lsturl.Get(2)
    req.InitializeHead(strUrl)
    hc.Execute(req, 1)
End Sub

Sub hc_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
    Log("ResponseSuccess")
    Log(map2Json(Response.GetHeaders))
    strResult = convertToHkDate(Response.GetHeaders.Get("date"))
    Response.Release
    CallSubDelayed2(strModule, strCallback, strResult)
End Sub

Sub hc_ResponseError (Response As OkHttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    Log("ResponseError")
    Log($"ResponseError. Reason: ${Reason}, Response: ${Response.ErrorResponse}"$)
    Response.Release
    CallSubDelayed2(strModule, strCallback, strResult)
End Sub

The okHttpResponse instance contains Headers in form as a Map:
okHttpResponse.GetHeaders as map:
{
    "x-frame-options": [
        "SAMEORIGIN"
    ],
    "content-type": [
        "text\/html"
    ],
    "connection": [
        "keep-alive"
    ],
    "location": [
        "https:\/\/hk.yahoo.com\/?p=us"
    ],
    "content-language": [
        "en"
    ],
    "content-security-policy": [
        "frame-ancestors 'self' https:\/\/*.techcrunch.com https:\/\/*.yahoo.com https:\/\/*.aol.com https:\/\/*.huffingtonpost.com https:\/\/*.oath.com https:\/\/*.verizonmedia.com https:\/\/*.publishing.oath.com; sandbox allow-forms allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-presentation; report-uri https:\/\/csp.yahoo.com\/beacon\/csp?src=ats&site=frontpage&region=US&lang=en-US&device=desktop&yrid=&partner=;"
    ],
    "date": [
        "Wed, 03 Jun 2020 10:07:50 GMT"
    ],
    "cache-control": [
        "no-store, no-cache, max-age=0, private"
    ],
    "x-xss-protection": [
        "1; report=\"https:\/\/csp.yahoo.com\/beacon\/csp?src=fp-hpkp-www\""
    ],
    "expires": [
        "-1"
    ],
    "set-cookie": [
        "RRC=st=1591178870&cnt=1; expires=Wed, 03-Jun-2020 10:08:20 GMT; path=\/; domain=.www.yahoo.com; HttpOnly"
    ],
    "content-length": [
        "12"
    ],
    "server": [
        "ATS"
    ],
    "strict-transport-security": [
        "max-age=31536000"
    ]
}

The sample coding is: sample coding

The working screen is:
HmiFaAo.png
 

Steve Kwok

Member
Licensed User
Only common library, okHttp required.
No extra libraries such as SPSntp nor Threading required.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
It is a mistake to use OkHttpClient instead of OkHttpUtils2 and it is a mistake to create a new OkHttpClient every request.

Cross platform solution:
B4X:
Sub GetDateFromHeaders (Url As String) As ResumableSub
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download(Url)
    Dim res As Long
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        If j.Response.GetHeaders.ContainsKey("date") Then
            Dim date As String = j.Response.GetHeaders.Get("date")
            date = date.Replace("[", "").Replace("]", "")
            Dim f As String = DateTime.DateFormat
            Try
                DateTime.DateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
                res = DateTime.DateParse(date)
            Catch
                Log(LastException)
            End Try
            DateTime.DateFormat = f
        End If
    End If
    j.Release
    Return res
End Sub

Usage:
B4X:
Wait For (GetDateFromHeaders("https://www.google.com")) Complete (Time As Long)
If Time <> 0 Then
    Log($"Network time: $DateTime{Time}"$)
End If

Depends on: OkHttpUtils2 or iHttpUtils2 in B4i.
 

Sandman

Expert
Licensed User
Longtime User
Top