Saturday, February 4, 2017

Prevent user from setting previous DateTime in android

This can be achieved in two ways.
1st Way:
 package com.example.datetimedemo;  
 import java.util.Calendar;  
 import java.util.Date;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.text.format.DateFormat;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.DatePicker;  
 import android.widget.TextView;  
 import android.widget.TimePicker;  
 import android.widget.Toast;  
 public class MainActivity extends Activity{  
   DatePicker datePicker;  
   TimePicker timePicker;  
   TextView textView;  
   Date currentDate,selectedDate;  
   Calendar calendar;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     try {  
       setContentView(R.layout.main_layout);    
       textView = (TextView)findViewById(R.id.textView1);  
       datePicker = (DatePicker)findViewById(R.id.datePicker1);  
       timePicker = (TimePicker)findViewById(R.id.timePicker1);  
       calendar = Calendar.getInstance();  
       Button button = (Button)findViewById(R.id.button1);  
       button.setOnClickListener(new OnClickListener() {  
         @Override  
         public void onClick(View v) {  
           int currentDay = calendar.get(Calendar.DAY_OF_MONTH);  
           int currentMonth = calendar.get(Calendar.MONTH);  
           int currentYear = calendar.get(Calendar.YEAR) - 1900;  
           int currentHour = calendar.get(Calendar.HOUR_OF_DAY);  
           int currentMin = calendar.get(Calendar.MINUTE);  
           currentDate = new Date(currentYear, currentMonth, currentDay, currentHour, currentMin);  
           int selectedYear = datePicker.getYear();  
           int selectedDay = datePicker.getDayOfMonth();  
           int selectedMonth = datePicker.getMonth();  
           int selectedHour = timePicker.getCurrentHour();  
           int selectedMin = timePicker.getCurrentMinute();  
           selectedDate = new Date(selectedYear - 1900, selectedMonth, selectedDay, selectedHour, selectedMin);  
           if(selectedDate.compareTo(currentDate)<0){  
             Toast.makeText(getApplicationContext(), "Cannot set previous datetime.", Toast.LENGTH_SHORT).show();  
             textView.setText("");  
           }  
           else {  
             textView.setText(DateFormat.format("hh:mm a dd/MMM/yyyy", selectedDate)); //Output: 03:06 pm 07/Apr/2014  
           }  
         }  
       });  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
 }  
Create layout:
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical" >  
   <ScrollView  
     android:id="@+id/scrollView1"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content" >  
     <LinearLayout  
       android:layout_width="match_parent"  
       android:layout_height="match_parent"  
       android:gravity="center_horizontal"  
       android:orientation="vertical" >  
       <DatePicker  
         android:id="@+id/datePicker1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:calendarViewShown="false" />  
       <TimePicker  
         android:id="@+id/timePicker1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content" />  
       <Button  
         android:id="@+id/button1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:text="Done" />  
       <TextView  
         android:id="@+id/textView1"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:layout_marginTop="15dp"  
         android:text="TextView" />  
     </LinearLayout>  
   </ScrollView>  
 </LinearLayout>  
2nd Way: 
2nd way of implementing above stuff is mentioned as shown below. Only slight change includes, user cannot select datetime before our predefined datetime. i.e. If we want that user should not select datetime before 20 min if he does that then will display message saying you cannot select past datetime. Assuming the same layout.
 package com.example.datetimedemo;  
 import java.text.SimpleDateFormat;  
 import java.util.Calendar;  
 import java.util.Date;  
 import android.annotation.SuppressLint;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.DatePicker;  
 import android.widget.TextView;  
 import android.widget.TimePicker;  
 import android.widget.Toast;  
 public class MainActivity extends Activity{  
   DatePicker datePicker;  
   TimePicker timePicker;  
   TextView textView;  
   Date currentDate,selectedDate;  
   Calendar calendar;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     try {  
       setContentView(R.layout.main_layout);    
       textView = (TextView)findViewById(R.id.textView1);  
       datePicker = (DatePicker)findViewById(R.id.datePicker1);  
       timePicker = (TimePicker)findViewById(R.id.timePicker1);  
       calendar = Calendar.getInstance();  
       Button button = (Button)findViewById(R.id.button1);  
       button.setOnClickListener(new OnClickListener() {  
         @SuppressLint("SimpleDateFormat")  
         @Override  
         public void onClick(View v) {  
           Calendar cal = Calendar.getInstance();  
           cal.add(Calendar.MINUTE, 20); // Set our predefined value here.   
           calendar.clear();  
           calendar.set(Calendar.YEAR, datePicker.getYear());  
           calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());  
           calendar.set(Calendar.MONTH, datePicker.getMonth());  
           calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());  
           calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());            
           if(validateTime(cal.getTimeInMillis()/1000L, calendar.getTimeInMillis()/1000L)) {  
             SimpleDateFormat format = new SimpleDateFormat("hh:mm a dd/MMM/yyyy");  
             Date date = calendar.getTime();  
             textView.setText(format.format(date).toString()); //Output: 03:06 pm 07/Apr/2014  
             Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();  
           }else {  
             Toast.makeText(MainActivity.this, "Wrong", Toast.LENGTH_SHORT).show();  
           }  
         }  
       });  
     } catch (Exception e) {  
       e.toString();  
     }  
   }  
   private boolean validateTime(long current, long selected) {  
     if(selected > current)  
       return true;  
     return false;  
   }  
 }  

2 comments :

  1. if we don't want to show time between 12pm to 11am and not less than time and date than current time and date

    ReplyDelete
  2. Your code is working well for the date but not for time. My requirement is to prevent the user to select past time as well... So please help me full fill my requirement.

    ReplyDelete