Sie sind auf Seite 1von 3

13,291,254 members (62,609 online) Sign in

Search for articles, questions, tips


articles Q&A forums lounge

Learn Date and Time in Android


Val Okafor, 13 Jul 2015

5.00 (1 vote) Rate this:

Working with date and time is one of the common task Android developers perform.

Working with date and time is one of the common task Android developers perform. The framework provides a lot of tools and helper classes to help developers work with date and time in
Android so we will start our tutorial by examining the common terms and concept that you will encounter when you work with Android DateTime.
CodeProject

Android Date and Time Basics


1. Date this refers to a point in time, for example the moment you are reading this blog post can be represented by a date. The values for a date mostly but not alwayscome from
System.currentTimeInMillis.
2. DateTime refers to two sides of the same moment the date and time. You can refer to a person only by their first name (and this can be likened to a date) or you can refer to a
person by their first and last name and this can be likened to Datetime. Both represents the same person.
3. CurrentTimeInMillis this refers to the number of seconds that have elapsed since UnixTime which is January 1, 1970. In Android this number is returned as a long primitive type.
4. Calendar when we say a moment in time, are we talking about the minute or the hour of the day, or the day of the month, or the month of the year and so fourth. Calendar is an
abstract class that breaks down a Date instance down to integer representation of YEAR, MONTH, DAY, HOUR, etc. This way you can say if MONTH == MARCH AND DAY_OF_MONTH
== 5 alert Happy Birthday!.
5. GregoryCalender this is subclass of the Calendar class that represents Calendar as we know it in the western world and some argue in the rest of the world. Unless you have a very
strong reason not, you may want to use GregoryCalendar instead of the Calendar.
6. DateFormat you probably do not want to display date in your app as 521365987401202 which is the long value that the System.currentTimeInMillis may return. Instead you want to
display date in human readable format. You use DateFormat and some of its static classes to format date and to parse string representation of dates back to date.
7. SimpleDateFormat apparently the versatile DateFormat needs some improvement and it got one called SimpleDateFormat which formats a date into locale-sensitivestring
representation of date. With this, the string representation of the second day of the month of June 2015 will be June 2, 2015 or 6/2/2015 in the US, while in Europe the same will be
represented as 2 June, 2015 or 2/6/2015.
8. DateUtils if you want to write code logic in Android to calculate how many minutes have elapsed from the time you went to sleep until when you woke up from sleep, the DateUtil
will come to your rescue. It contains date related utilities to calculate elapsed time and date ranges.

Now that we have covered the basics of date time in Android, let us see how to put them to good use.

Formatting
The steps to format date and/or time in Android are

1. You get or generate the date that you want to display


2. You call on DateFormat or any of its sub classes such as SimpleDateFormat to format the date or
3. You manually format the date either by Stringconcatenationor other means

Here is an example of getting, formatting and displaying todays current date and time

Hide Copy Code

mTodayDate = (TextView)findViewById(R.id.today_date);

//Get or Generate Date


Date todayDate = new Date();

//Get an instance of the formatter


DateFormat dateFormat = DateFormat.getDateTimeInstance();

//If you want to show only the date then you will use
//DateFormat dateFormat = DateFormat.getDateInstance();

//Format date
String todayDateTimeString = dateFormat.format(todayDate);

//display Date
mTodayDate.setText(todayDateTimeString);

Of course there are many ways to obtain and display the current date and time such as this

Hide Copy Code


Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");


String formattedDateString = formatter.format(currentDate);
mTodayDate.setText(formattedDateString);

What of if you already have an existing date that you want to format, say the date is coming from a field in the database or from an API call. To format and display the date, you first have to
either obtain or convert the date to longand then you can create a method that accepts a long parameter and the format that you want the date to be displayed, here is an example

Hide Copy Code

private String getFormattedDate(long milliSeconds, String dateFormat)


{
// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);

// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}

And with that you can call the method like this

Hide Copy Code

long dateFromDatabase = getExistingDateFromSomewhere();


String dateToDisplay = getFormattedDate(dateFromDatabase, "yyyy-MM-dd");

Saving DateTime in Android


Saving date and time in Android is influenced by the persistence mechanism you are using and how you intend to use that date again and since SQLite database is the defacto persistence
mechanism in Android here are some options to save date and time:

1. String you can simply save your datetime as String (Text in SQLite) if all you want to do with the date going forward is display it. Also you can use DateFormat to parse the saved
String to date value and work with it later.
2. Long SQLite database and most database engines are not suitable for persisting non primitive objects like Java classes and since Date is a Java class you cannot save a field of type
Date to a SQLite database. You can however convert your date to milliseconds and save to database. For example here is how you can create a fictitious product table and save it to
database:
Hide Copy Code
private String createProductTable = "CREATE TABLE ProductTable(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"productname TEXT NOT NULL," +
"datecreated BIGINT";

and with this SQL statement we can create an object of type Product with a long date field like this:
Hide Copy Code
Product temp = new Product();
temp.productName = "Nice Product";
temp.dateCreated = System.currentTimeMillis();
saveDemo(temp);

and here is how we will save that product object to database.


Hide Copy Code
private long saveDemo(Product product){

SQLiteDatabase database = getWritableDatabase();

ContentValues values = new ContentValues();


values.put("productname", product.getProductName());
values.put("datecreated", product.getDateCreated());
Long result = database.insert("ProductTable", null, values);
database.close();
return result;
}

3. SQLite Datetype while SQLite does not havea storage class set aside for storing dates and/or times you can use SQLite built in datetime functions to work with date, with our
fictitious product table can now be created like this
Hide Copy Code
private String createProductTable2 = "CREATE TABLE ProductTable(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"productname TEXT NOT NULL," +
"datecreated DATETIME DEFAULT CURRENT_TIMESTAMP";

Android Date and Time Picker


The concept behind date and time pickers in Android is the same as in Web development limiting user input to known formats. Using picker dialog saves you from writing parsing logic to
parse every known format that your user may input date. Android provides ready to use dialogs that you can present to your users for them to use to select date and time that you can work
with in your app. The challenge sometimes, is after the user select the date in the dialog how do you work with the date in your Activity or Fragment.

Here are some steps that you can use to work with date and time that your users select in the picker dialog.

1. Create a Calendar or GregoryCalendar instance variable in your Activity or Fragment


2. Create a Picker DialogFragment
3. Set your Fragment as the target Fragment, so when then the user selects a date it will be delivered to your Fragment

For example if you have a Fragment called BirthDayFragment and you want to give your users a dialog to select their birthdays. When they select their birthday, you want to save that date in
the database. Here is what you can do:

1. Create a Person class with a property of type long to store the birthday as well as other properties you may need
2. In the BirthdayFragment.java create a member variable of type Calendar that stores the date the user selected from the dialog picker
3. Create a DialogFragment that implements DatePickerDialog and set your BirthdayFragment as the target Fragment
4. When user selects a date from the dialog picker, store the date in the Calendar variable in your Fragment
5. Convert the Calendar variable to long and save
6. Here is a code demo to illustrate these steps

Hide Shrink Copy Code

public class Person{


private int id;
private String name;
private long birthday;
}

//Create a person instance


Person person1 = new Person();
person1.setname("John Doe");
if (mBirthday != null){
person1.setbirthday(mBirthday.getTimeInMillis());
}

public GregorianCalendar mBirthday;

private void showDatePickerDialog() {


//fire up the logic show the date picker dialog
DialogFragment datePickerFragment = new BirthDatePickerDialogFragment();
datePickerFragment.setTargetFragment(BirthdayFragment.this, 0);
datePickerFragment.show(getFragmentManager(), "datePicker");

public static class BirthDatePickerDialogFragment extends DialogFragment


implements DatePickerDialog.OnDateSetListener{

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

// Create a new instance of DatePickerDialog and return it


return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
BirthDateFragment targetFragment = (BirthDateFragment)getTargetFragment();
if (year < 0){
targetFragment.mBirthday = null;
} else {
targetFragment.mBirthday = Calendar.getInstance();
targetFragment.mBirthday.set(year, monthOfYear, dayOfMonth);
}

I hope that this blog post helps you with working with date and time and Android.

<form action='//valokafor.us4.list-manage.com/subscribe/post?u=0600ce94a59d7720819aa3dd8&id=6e5492cf7d' class='frm' method='post'><input type='text' placeholder='Email


Address' name='EMAIL' /><input type='text' placeholder='First Name' name='FNAME' /><input type='hidden' name='b_0600ce94a59d7720819aa3dd8_6e5492cf7d' value='' />
<input type='submit' value="Send Me New Tutorials">
</form>

Follow Me
Follow @valokafor
<script>jQuery(window).load(function() { ThriveApp.load_script('twitter'); });</script>
<script>jQuery(window).load(function() { ThriveApp.load_script('google'); });</script>
<script type='IN/MemberProfile' data-format='inline' data-id='https://www.linkedin.com/in/valokafor'></script>
<script>jQuery(window).load(function() { ThriveApp.load_script('linkedin'); });</script>

The post Learn Date and Time in Android appeared first on Val Okafor.

License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Das könnte Ihnen auch gefallen