Get Current Date and Time in Android using Two Classes

Recently, I needed to get current date and time in android. I found two ways of doing it. They are by using the Calendar class and SimpleDateFormat class. So let’s see what method will be more simple and useful for you.

android-get-current-date-time

A simple outline of this post:

1.0 Using the Calendar Class
2.0 Using the SimpleDateFormat Class
3.0 My Thoughts
4.0 Helpful Comments

1.0 Using the Calendar Class

Here’s how to get android date and time using the Calendar Class.

// using Calendar class
Calendar ci = Calendar.getInstance();

String CiDateTime = "" + ci.get(Calendar.YEAR) + "-" + 
    (ci.get(Calendar.MONTH) + 1) + "-" +
    ci.get(Calendar.DAY_OF_MONTH) + " " +
    ci.get(Calendar.HOUR) + ":" +
    ci.get(Calendar.MINUTE) +  ":" +
    ci.get(Calendar.SECOND);

The output of the code above is:

2011-6-9 7:0:56

2.0 Using the SimpleDateFormat Class

And here’s how to get it using SimpleDateFormat Class.

// SimpleDateFormat Class
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
String newtime =  sdfDateTime.format(new Date(System.currentTimeMillis()));

SimpleDateFormat code output will be:

2011-06-09 19:00:56

3.0 My Thoughts

As you can see, using the calendar class seemed like it require us to code more. Also, I think I found a bug. My device calendar settings are correct. It is month of June, so ci.get(Calendar.MONTH) must return “6” but it returns “5” so I had to add “1” to make the output correct.

In my case, I used the SimpleDateFormat class since I don’t really have to synchronize it. It is easy to format – you can just use its time pattern strings (in our example “yyyy-MM-dd HH:mm:ss”).

But please be aware that it was said in the docs that SimpleDateFormat is NOT thread safe when it comes to Synchronization.

You should read more about the Android’s Calendar Class and SimpleDateFormat Class. Thanks for sharing your thoughts about getting the current date and time in Android!

4.0 Helpful Comments

I love reading useful comments and so we will highlight them by including it in our post. Thanks Kovica and Charuta!

According to Kovica:

You didn’t find any bugs, because if you look closely at the docs for the java.util.Calendar class, you’ll see that JANUARY = 0 http://developer.android.com/reference/java/util/Calendar.html#JANUARY), so JUNE = 5 http://developer.android.com/reference/java/util/Calendar.html#JUNE)

Charuta Said:

You could use the Time class, it’s a faster implementation of Calendar class. http://developer.android.com/reference/android/text/format/Time.html

How about you, do you have any other solution or thought about getting current date and time in Android? Drop it in the comments section below! Thanks!

Multiple Android Button Tutorial

Multiple Android Button Tutorial

Hi guys! Today we’re gonna do an example application of android Push Buttons.

Push-buttons can be pressed, touched, or clicked by the user to invoke an event or action in your application.

This example will show you how to make two android buttons working (you can add more if you want).

It also uses an Android toast so if you’re not yet familiar with it, you may visit also view my post about Android Toasts here.

So, after creating a new project, we will modify two files.

The main activity file, which is in this case, the AndroidButtons.java and the layout file which is the main.xml

AndroidButtons.java

package com.example.AndroidButtons;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class AndroidButtons extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    try {
    View.OnClickListener handler = new View.OnClickListener(){
        public void onClick(View v) {
            //we will use switch statement and just
            //get thebutton's id to make things easier
            switch (v.getId()) {

                case R.id.ShowToastBtn: //toast will be shown
                    Toast.makeText(getBaseContext(), "You Clicked Show Toast Button!", Toast.LENGTH_SHORT).show(); 
                    break;
                case R.id.FinishBtn: //program will end
                    finish();
                    break;
            }
        }
    };
        
    //we will set the listeners
    findViewById(R.id.ShowToastBtn).setOnClickListener(handler);
    findViewById(R.id.FinishBtn).setOnClickListener(handler);
        
    }catch(Exception e){
         Log.e("Android Button Tutorial", e.toString());
    }  
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
    android:layout_width="98px"
    android:layout_height="wrap_content"
    android:text="Show Toast" 
    android:id="@+id/ShowToastBtn">
    </Button>
    
    <Button
    android:layout_width="98px"
    android:layout_height="wrap_content"
    android:text="Finish" 
    android:id="@+id/FinishBtn">
    </Button>
</LinearLayout>

When you run this script it will look like this:

SC20110720-085607

When you click the “Show Toast” Button, it will look like this:

SC20110720-085600

When you click “Finish”, obviously, the program will end. Haha!

Android Toast Tutorial

What is Android Toast? The Android Toast is a view containing a quick little message for the user. When the toast is shown to the user, appears as a floating view over the application so it will never receive focus. The idea is to be as unobtrusive as possible, for example you want to instantly display information to user while they are using the your app. This tutorial will show you how to create a simple Android Toast using the toast class.

Android Toast Tutorial

I feel hungry now. :))

package com.example.AndroidToastTutorial;

import android.app.Activity;
import android.os.Bundle;
//import the toast widget
import android.widget.Toast;

public class AndroidToastTutorial extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //"This is the Toast message" will appear when you run this code
        Toast.makeText(getBaseContext(), "This is the Toast message", Toast.LENGTH_SHORT).show();
    }
}

The output of this code will look like the lower part of the image above (below the android logo and toasted bread). More info here. So that’s it! :)

Fixed: Android requires compiler compliance level 5.0. Please fix project properties.

When I tried to import an existing eclipse android project to my new workspace, I encountered an error:

Android requires compiler compliance level 5.0. Please fix project properties.

So here’s what I did to fix this problem:

Right Click Project > Properties > Java Build Path > Order and Export Tab > Check Your Android SDK Version on the list (I got Android 2.2)

Fixed: Android requires compiler compliance level 5.0. Please fix project properties.

Then…

Right Click Project > Properties > Java Compiler > Check Enable Project Specific Settings > Select Compiler Compliance Level
In my case, I had to changed the compiler compliance level from 1.6 to 1.5

jcompiler

And that solves my problem. :)