Aug 4, 2014

Get time of system

Example to get time (in millisecond and nanosecond) from System, and get instance of Calendar to get current time.


package com.example.androidtime;

import java.util.Calendar;

import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.os.Bundle;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TextView tim = (TextView)findViewById(R.id.tim);
        TextView cal = (TextView)findViewById(R.id.cal);
        
        tim.setText(
         "currentTimeMillis: " + System.currentTimeMillis() + "\n" +
         "nanoTime" + System.nanoTime() + "\n"
         );
        
        Calendar calendar = Calendar.getInstance(); 
        cal.setText(
         "YEAR: " + calendar.get(Calendar.YEAR) + "\n" +
         "MONTH: " + calendar.get(Calendar.MONTH) + "\n" +
         "DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH) + "\n" +
         "HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY) + "\n" +
         "MINUTE: " + calendar.get(Calendar.MINUTE) + "\n" +
         "SECOND: " + calendar.get(Calendar.SECOND) + "\n"
         );

    }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidtime.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android-coding.blogspot.com" />
    <TextView
        android:id="@+id/tim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/cal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

2 comments:

  1. There is mistake in the code: calendar.get(Calendar.MONTH) gets the month index starting with 0, so index 7 is actually august. You need to increment the calendar.get(Calendar.MONTH) by one to get the correct month number.

    ReplyDelete
  2. "MONTH: " + (calendar.get(Calendar.MONTH) + 1) + "\n" +

    ReplyDelete

Infolinks In Text Ads