How to Set Mobile System Time and Date in Android

How to get current time and date in Android

You could use:

import java.util.Calendar

Date currentTime = Calendar.getInstance().getTime();

There are plenty of constants in Calendar for everything you need.

Check the Calendar class documentation.

Programmatically set System Time

As it turns out, the answer did lie in the referenced question found here. However, the command is different for Android 7 (and possibly 6, I have not tested) devices. I do not have the reputation to comment over there, so if someone wishes to paste/reference this answer on that question, go right ahead.

The date code I used was in the format MMddhhmmyy, rather than yyyyMMdd.hhmmss; this works for me on Android 7. I also removed the appended '-s'. The full working code I used to set the system time is below. Again it should be noted that this requires rooting the device so is only useful in certain scenarios like mine.

     try {

Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
String command = "date 1123104017\n";
// Log.e("command",command);
os.writeBytes(command);
os.flush();
os.writeBytes("exit\n");
os.flush();
process.waitFor();

} catch (InterruptedException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}

The date I entered, for clarity, is November 23rd 2017 at 10:40 AM.

How to get android system date and time format in app

Use the following:

DateFormat.is24HourFormat(context);

Source: https://developer.android.com/reference/android/text/format/DateFormat.html#is24HourFormat(android.content.Context)

Display the current time and date in an Android application

Okay, not that hard as there are several methods to do this. I assume you want to put the current date & time into a TextView.

String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);

There is more to read in the documentation that can easily be found here
. There you'll find more information on how to change the format used for conversion.



Related Topics



Leave a reply



Submit