Android Programming : Getting current Date and Time


To get date and time, we have used the Calendar class to get the instance to phone clock:

Calendar cal = Calendar.getInstance(TimeZone.getDefault());

TimeZone would be the one set in the phone.

 

Finally we have used SimpleDateFormat to get the time in the particular format:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a", Locale.getDefault());

 

Below is the source code from my MainActivity class:

 

package com.aslsoft.pocapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import android.os.Bundle;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  TextView tv = (TextView) findViewById(R.id.tv);
  Calendar cal = Calendar.getInstance(TimeZone.getDefault());
  
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a", Locale.getDefault());
  tv.setText("Date Time : " + cal.getTime().toLocaleString() + "\nTime :" + sdf.format(cal.getTime()) );
  
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

 

Result:

 

clip_image002

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s