How to create date object from Date picker and Time Picker

In this android programming source code example, we are going to create date object from Date picker and Time Picker.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to create date object from Date picker and Time Picker.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_centerInParent="true"
        android:onClick="CreateDateObject"
        android:text="CreateDateObject"
        android:textColor="#ffffff"
        android:textSize="15sp"
        android:textStyle="bold" />

</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Date;

public class DatePickerAndTimePickerActivity18 extends AppCompatActivity {
    private int year, monthofyear, dayofmonth, hourofday, minute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker_and_time_picker18);
    }

    public void CreateDateObject(View view){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthofyear);
        calendar.set(Calendar.DATE, dayofmonth);
        calendar.set(Calendar.HOUR_OF_DAY, hourofday);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date date = calendar.getTime();
        Toast.makeText(DatePickerAndTimePickerActivity18.this,"date Object: 0"+date, Toast.LENGTH_LONG).show();
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.