Get current Server Date/Time in Android
Get current Server Date/Time in Android
In our android app, when we want a process to get current system time and date, then there's only question of
- What if user change it's device time zone or clock to hack our app or game time functionality.
For that you can use two apis url to fetch Internet Server Time and Date
You can use any api to get that time. Both apis have different response structure, but there's a same format which is a Json format.
So, let's start an Android Project to get values from Internet server date time.
Create an Android Project and name it and create and Http handler.java file to handle all http json data and it's response.
Http Handler.java to handle all http url json data.
package studio.harpreet.sampleproject;
import android.util.Log;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
After that in our XML file create some text views to set fetched values.
XML activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="5dp"
tools:context=".internet_date_time">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/date_year"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/date_month"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/date_day"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/date_hour"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/date_minute"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/date_seconds"
android:padding="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Date/Time"
android:id="@+id/date_time_btn"/>
</LinearLayout>
And in Java file, Get all values from Json api by Json parsing and set values on Text Views.
Java File
package studio.harpreet.sampleproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class internet_date_time extends AppCompatActivity {
String JsonString = "http://worldtimeapi.org/api/timezone/America/Argentina/Salta";
TextView year,month,day,hour,minute,sec;
Button get_btn;
String s_year;
String s_month;
String s_day;
String s_hour;
String s_min;
String s_sec;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_internet_date_time);
year = findViewById(R.id.date_year);
month = findViewById(R.id.date_month);
day = findViewById(R.id.date_day);
hour = findViewById(R.id.date_hour);
minute = findViewById(R.id.date_minute);
sec = findViewById(R.id.date_seconds);
get_btn = findViewById(R.id.date_time_btn);
get_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// new GetDateTime().execute();
String url = "https://api.whatsapp.com/send?phone=917696674685&text=Hello,%20I%20need%20to%20know%20more%20about";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
intent.setPackage("com.whatsapp.w4b");
startActivity(intent);
}
});
}
public class GetDateTime extends AsyncTask<Void,Void,Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
HttpHandler hh = new HttpHandler();
String jsonstr = hh.makeServiceCall(JsonString);
Log.e("TAG", "doInBackground: response from url: "+jsonstr );
try {
JSONObject obj = new JSONObject(jsonstr);
String abbreviation = obj.getString("abbreviation");
String ip = obj.getString("client_ip");
String date_time = obj.getString("datetime"); // we will substring this to get exact time and date
int day = obj.getInt("day_of_week");
String example = "2022-01-08T18:43:49.225815+05:30";
s_year= date_time.substring(0,4); //1,2,3,4 character position returns
s_month= date_time.substring(5,7);//6,7 character returns
s_day = date_time.substring(8,10);
s_hour = date_time.substring(11,13);
s_min = date_time.substring(14,16);
s_sec = date_time.substring(17,19);
//Sorry there's an error if you set your text on textview from here, we have to set this text in onpostexecute..
Log.e("TAG", "doInBackground: abbr: "+abbreviation
+"ip: "+ip+" day: "+day);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
year.setText(String.format("Year: %s", s_year));
month.setText(String.format("Month: %s", s_month));
day.setText(String.format("Day: %s", s_day));
hour.setText(String.format("Hour: %s", s_hour));
minute.setText(String.format("Min: %s", s_min));
sec.setText(String.format("Seconds: %s", s_sec));
}
}
}
Subscribe to Harpreet studio on Youtube
Like Harpreet Studio on Facebook
Follow me on Instagram
No comments