I'm super-new in Java and Android Studio. I've started app with date functionality. I've created 3 buttons in app menu. One is button back, date, and button forward.
case 1. When you start the app, current date shows up on date button, when you click button back or forward that date on the middle button changes accordingly by one day.
case 2. When you click date button itself (for the first time) it pops out the date picker with the date from the button highlighted, you can change the date and it changes the date button accordingly from the picker.
case 3. But when I use buttons forward and back after the picker was out (once) date still changes on the button, but it does not highlights in the picker. It only highlights correctly first time around, it also highlights correctly when changing date via picker, but not via back and forward buttons.
What am I doing wrong (beside using deprecated methods? ;-)). Any input will be very appreciated.
//variables for date
int year_x,month_x,day_x;
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
MenuItem dynamicDate;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
dynamicDate = menu.findItem(R.id.action_date);
Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH) + 1;
day_x = cal.get(Calendar.DAY_OF_MONTH);
String currentDateString = (day_x<10?("0"+day_x):(day_x)) + "-" + (month_x<10?("0"+month_x):(month_x)) + "-" + year_x;
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
dynamicDate.setTitle(currentDateString);
return true;
}
public DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year_xk, int month_xk, int day_xk) {
Calendar cal = Calendar.getInstance();
cal.set(year_xk, month_xk, day_xk);
Date dateAfterChange = cal.getTime();
String dateAfterChangeString = df.format(dateAfterChange);
dynamicDate.setTitle(dateAfterChangeString);
//Toast.makeText(MainActivity.this, "you clicked date", Toast.LENGTH_SHORT).show();
}
};
#Override
public Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 0473) {
String currentDateString = dynamicDate.getTitle().toString();
//DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
return new DatePickerDialog(this, myDateListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH));
}
return null;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_back) {
String currentDateString = dynamicDate.getTitle().toString();
//DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.DATE, -1);
Date dateDayBefore = cal.getTime();
String dateDayBeforeString = df.format(dateDayBefore);
dynamicDate.setTitle(dateDayBeforeString);
//return true;
}
if (id == R.id.action_date) {
showDialog(0473);
}
if (id == R.id.action_forward) {
String currentDateString = dynamicDate.getTitle().toString();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.DATE, +1);
Date dateDayAfter = cal.getTime();
String dateDayAfterString = df.format(dateDayAfter);
dynamicDate.setTitle(dateDayAfterString);
//return true;
}
return super.onOptionsItemSelected(item);
}
I had used removeDialog (when back and forward buttons where pressed) for onCreateDialog to work each time the date was pressed.
Related
I use Material design to implement Date Picker but I need to disabled the user select some specific dates how I can implement this ?
Below is my code:
button=findViewById(R.id.select_date);
Calendar calendar=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
long today=MaterialDatePicker.todayInUtcMilliseconds();
CalendarConstraints.Builder cons=new CalendarConstraints.Builder();
cons.setValidator(DateValidatorPointForward.now());
MaterialDatePicker.Builder builder=MaterialDatePicker.Builder.datePicker();
builder.setTitleText("Select booking date");
builder.setSelection(today);
builder.setCalendarConstraints(cons.build());
MaterialDatePicker materialDatePicker=builder.build();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Date Picker");
}});
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
System.out.println(materialDatePicker.getHeaderText());
}
});
}
}
The values in this Calendar[] are explicitly disabled (not selectable). This option can be used together with setSelectableDays(Calendar[] days): in case there is a clash setDisabledDays(Calendar[] days) will take precedence over setSelectableDays(Calendar[] days)
String[] holidays = {"07-03-2018","05-03-2018","10-03-2018"};
java.util.Date date = null;
for (int i = 0;i < holidays.length; i++) {
try {
date = sdf.parse(holidays[i]);
} catch (ParseException e) {
e.printStackTrace();
}
calendar = dateToCalendar(date);
System.out.println(calendar.getTime());
List<Calendar> dates = new ArrayList<>();
dates.add(calendar);
Calendar[] disabledDays1 = dates.toArray(new Calendar[dates.size()]);
dpd.setDisabledDays(disabledDays1);
}
private Calendar dateToCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
This question already has answers here:
Android calculate days between two dates
(17 answers)
How to get number of days between two calendar instance?
(12 answers)
Closed 2 years ago.
i create a booking hotels apps and it hase 3 textview and 2 button to choose the date. if button click it display a date and selected date will displayed to 2 textview. how to display the day between dates in the third textview??
here's my code ( the third textview not displayed as day between dates)
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
tvDateResult = (TextView) findViewById(R.id.tv_dateresult);
res = findViewById(R.id.tv_dateresult1);
ress = findViewById(R.id.tv_dateresult2);
btDatePicker = (Button) findViewById(R.id.bt_datepicker);
date = findViewById(R.id.bt_datepicker1);
get = findViewById(R.id.getprice);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDateDialog2();
}
});
btDatePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDateDialog();
}
});
}
private void showDateDialog2() {
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
res.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
if(tvDateResult !=null || res !=null) {
try {
String a = tvDateResult.getText().toString();
String b = res.getText().toString();
Date aa = dateFormatter.parse(a);
Date bb = dateFormatter.parse(b);
long diff = bb.getTime() - aa.getTime() / 24 * 60 * 60 * 1000;
ress.setText((int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
private void showDateDialog(){
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
tvDateResult.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
Declare 2 global variables:
Calendar date1 = null, date2 = null;
In onDateSet method of both date pickers, save the selected date in global variables.
In onDateSet of first date picker,
Calendar newDate = Calendar.getInstance();
date1 = newDate
updateTextView()
Similarly, In onDateSet of second date picker,
Calendar newDate = Calendar.getInstance();
date1 = newDate
updateTextView()
Call a method from both onDateSet methods.
private void updateTextView() {
if(date1 != null && date2 != null) {
tvDateResult .setText(dateFormatter.format(daysBetween(date1,date2)));
}
}
public static long daysBetween(Calendar startDate, Calendar endDate) {
// Make sure we don't change the parameter passed
Calendar newStart = Calendar.getInstance();
newStart.setTimeInMillis(startDate.getTimeInMillis());
newStart.set(Calendar.HOUR_OF_DAY, 0);
newStart.set(Calendar.MINUTE, 0);
newStart.set(Calendar.SECOND, 0);
newStart.set(Calendar.MILLISECOND, 0);
Calendar newEnd = Calendar.getInstance();
newEnd.setTimeInMillis(endDate.getTimeInMillis());
newEnd.set(Calendar.HOUR_OF_DAY, 0);
newEnd.set(Calendar.MINUTE, 0);
newEnd.set(Calendar.SECOND, 0);
newEnd.set(Calendar.MILLISECOND, 0);
long end = newEnd.getTimeInMillis();
long start = newStart.getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
}
Reference: How to get number of days between two calendar instance?
I am using datepickerdialog. it run properly on kitkat but when i run application on lollipop and when i click on edit text it opens a datepickerdialog box but when i select date it give unfortunately stop error. Below is the code for datepicker on edittext.
private void setDateTimeField() {
fromLabel.setOnClickListener(this);
toLabel.setOnClickListener(this);
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); //yyyy/MM/dd HH:mm:ss
final Date date = new Date();
final String u = dateFormat.format(date);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
from1 = dateFormatter.format(newDate.getTime());
diff1 = newDate.getTimeInMillis();
long d = date.getTime();
if((newDate.getTime()).equals(date)||(newDate.getTime()).after(date)){
long d1 = (diff1 / (24 * 60 * 60 * 1000) - d / (24 * 60 * 60 * 1000)) + 1;
if(d1>30){
total.setVisibility(View.VISIBLE);
total.setText("Booking not allowed as the Date given is outside Advance Booking Period");
avail.setVisibility(View.GONE);
}
else{
total.setVisibility(View.GONE);
fromLabel.setText(from1);
toLabel.setText(null);
to=null;
avail.setVisibility(View.GONE);
from=fromLabel.getText().toString();
}
}
else{
total.setVisibility(View.VISIBLE);
total.setText("Choose date after or equals to current date");
fromLabel.setText("");
toLabel.setText(null);
from=null;
to=null;
}
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
fromDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.Done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
dialog.cancel();
if(type.equals("According to time"))
{
int cnt=-1;
if(from1.equals(u)){
cnt = 1;
loadTimeSpinnerDataATT(text,from,cnt);
}
else if(total.getText()=="Choose date after or equals to current date")
{
}
else if(total.getText()=="Booking not allowed as the Date given is outside Advance Booking Period")
{
}
else
{cnt = 0;
loadTimeSpinnerDataATT(text,from,cnt);
}
}
}
}
});
}
public void onClick(View view) {
if(view == fromLabel) {
fromDatePickerDialog.show();
} else if(view == toLabel) {
toDatePickerDialog.show();
}
}
public void onClose(DialogInterface dialogInterface)
{
}
}
Try it, may help you,
Date picker error resloved here
Link For Date picker
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
// for date picker
EditText m3_DateDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m3_DateDisplay = (EditText) findViewById(R.id.datepick);
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Show selected date
StringBuilder dateValue1 = new StringBuilder().append(day).append("-")
.append(month + 1).append("-").append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
m3_DateDisplay.setFocusable(false);
m3_DateDisplay.setInputType(InputType.TYPE_NULL);
m3_DateDisplay.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
// return new DatePickerDialog(this, pickerListener, year, month,
// day);
// ///Only Show till Date Not More than That.
DatePickerDialog dialog = new DatePickerDialog(this,
pickerListener, year, month, day);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
StringBuilder dateValue = new StringBuilder().append(day)
.append("-").append(month + 1).append("-").append(year)
.append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
}
};
}
change minimum api-11 in manifest
I have two date pickers which are connected to each other as when I change the date of the first picker the second ones date is also changed automatically ,
the two pickers have a listener called on date change listener, as follows
public class birthDate extends Activity{
Calendar c = Calendar.getInstance();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH);
int currentDay = c.get(Calendar.DAY_OF_MONTH);
TextView birthDatetv;
DatePicker birthDayDatePicker,periodDatePicker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.birthdate);
birthDatetv = (TextView)findViewById(R.id.textViewDateBirth);
birthDayDatePicker = (DatePicker)findViewById(R.id.DatePickerBirthDay);
periodDatePicker = (DatePicker)findViewById(R.id.DatePickerPeriod);
periodDatePicker.init(currentYear, currentMonth, currentDay, new OnDateChangedListener()
{
#Override
public void onDateChanged(DatePicker periodDatePicker, int currentYear, int currentMonth,int currentDay) {
// TODO Auto-generated method stub
birthDateCalculations();
}
});
birthDayDatePicker.init(currentYear, currentMonth, currentDay, new OnDateChangedListener () {
#Override
public void onDateChanged(DatePicker birthDayDatePicker, int currentYear, int currentMonth, int currentDay) {
// TODO Auto-generated method stub
periodDateCalculations();
}
});
}
As I mentioned before, the pickers are connected, so when I change one picker date the other is also changed so the two listeners for the two date pickers will be invoked,, I just want the listener that is involved with the picker that the user changed its date to be invoke ,, Any idea how to do that ?
Here is the methods that the listeners do if it may help
public void birthDateCalculations ()
{
Calendar start = Calendar.getInstance();
int periodYear = periodDatePicker.getYear();
int periodMonth = periodDatePicker.getMonth();
int periodDay = periodDatePicker.getDayOfMonth();
start.set(periodYear, periodMonth, periodDay);
birthDayDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
periodDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
Date periodDate = start.getTime();
int daysToAdd = 280;
Calendar cal = Calendar.getInstance();
cal.setTime(periodDate);
cal.add(Calendar.DAY_OF_MONTH,daysToAdd );
System.err.println("-----" +cal.getTime());
int birthYearAfterCalc = cal.getTime().getYear()+1900;
System.err.println("birthYearAfterCalc-----" + birthYearAfterCalc);
int birthMonthAfterCalc = cal.getTime().getMonth();
System.err.println("birthMonthAfterCalc----" + birthMonthAfterCalc);
int birthDayAfterCalc = cal.getTime().getDate();
System.err.println("birthDayAfterCalc"+birthDayAfterCalc);
//user edit period to get birth
if( periodDay <= currentDay && periodMonth <= currentMonth && periodYear <= currentYear){
//the program runs normally
birthDayDatePicker.updateDate(birthYearAfterCalc, birthMonthAfterCalc, birthDayAfterCalc);
}
else {
new AlertDialog.Builder(birthDate.this)
.setTitle("Wrong Data Input!")
.setMessage("Error in period date input")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
periodDatePicker.updateDate(currentYear,currentMonth, currentDay);
birthDayDatePicker.updateDate(currentYear, currentMonth, currentDay);
}
}
public void periodDateCalculations ()
{
Calendar start2 = Calendar.getInstance();
// get the chosen date from birth date picker
int birthYear = birthDayDatePicker.getYear();
int birthMonth = birthDayDatePicker.getMonth();
int birthDay = birthDayDatePicker.getDayOfMonth();
//set the chosen date to calendar instance
start2.set(birthYear, birthMonth, birthDay);
birthDayDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
periodDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
//get the date
Date birthDate = start2.getTime();
//int constrain = currentMonth + 9;
int daysToAdd = -280;
//another instance from calendar
Calendar cal2 = Calendar.getInstance();
//set birth date chosen to calendar
cal2.setTime(birthDate);
//add -280 day to birth day to get period date
cal2.add(Calendar.DAY_OF_MONTH,daysToAdd);
System.err.println("-----" +cal2.getTime());
int periodYearAfterCalc = cal2.getTime().getYear()+1900;
System.err.println("periodYearAfterCalc-----" + periodYearAfterCalc);
int periodMonthAfterCalc = cal2.getTime().getMonth();
System.err.println("periodMonthAfterCalc----" + periodMonthAfterCalc);
int periodDayAfterCalc = cal2.getTime().getDate();
System.err.println("periodDayAfterCalc"+periodDayAfterCalc);
//edit birth date picker from user
if(birthDay >= currentDay && birthMonth >= currentMonth && birthYear >= currentYear){
//the program runs normally
periodDatePicker.updateDate(periodYearAfterCalc, periodMonthAfterCalc, periodDayAfterCalc);
}
else{
new AlertDialog.Builder(birthDate.this)
.setTitle("Wrong Data Input!")
.setMessage("birth day input error")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
birthDayDatePicker.updateDate(currentYear,currentMonth, currentDay);
periodDatePicker.updateDate(currentYear, currentMonth, currentDay);
}
}
}
what you could do is set the corresponding listener to null when the other one takes action, and then after the task, you could turn it back on.
for example:
periodDatePicker.init(currentYear, currentMonth, currentDay, new OnDateChangedListener()
{
#Override
public void onDateChanged(DatePicker periodDatePicker, int currentYear, int currentMonth,int currentDay) {
// TODO Auto-generated method stub
birthDayDatePicker.init(currentYear, currentMonth, currentYear, null);
birthDateCalculations();
restartBirthDayDatePickerListener();
// ^here you turn back on that init command that we have just set to null.
}
});
not a glamorous solution, but perhaps you can make heads or tails of it.
I have two String variables - time1 and time2. Both contain value in the format HH:MM. How can I check:
If the current time is within
time1 and time2?
time1 will happen in the nearest
hour?
Upd.
I've implemented the following to convert time1 to Date format. But it uses depreciated methods:
Date clTime1 = new Date();
SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
try {
clTime1 = timeParser.parse(time1);
} catch (ParseException e) {
}
Calendar now = Calendar.getInstance();
clTime1.setYear(now.get(Calendar.YEAR) - 1900);
clTime1.setMonth(now.get(Calendar.MONTH));
clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
System.out.println(clTime1.toString());
Convert the two strings to Date
objects (which are also time objects)
Create a new Date object.
This will
contain the current time.
Use the
Date.before() and Date.after() methods to determine if
you are in the time interval.
EDIT: You should be able to use this directly (and no deprecated methods)
public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
//yada yada
}
}
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
This is what I used as simple function and it worked for me:
public static boolean isTimeWith_in_Interval(String valueToCheck, String startTime, String endTime) {
boolean isBetween = false;
try {
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(startTime);
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(endTime);
Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);
if (time1.before(d) && time2.after(d)) {
isBetween = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return isBetween;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Date EndTime = dateFormat.parse("10:00");
Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
if (CurrentTime.after(EndTime))
{
System.out.println("timeeee end ");
}
Don't forget to surrounded with a try catch block
if you want time between after 9PM to before 9Am you can use following condition..
if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
// do your stuffs
}
Look into the Calendar class. It has the methods to support what you are asking. Date is deprecated and not recommended to use.
Here is the link to the API. Calendar
About the usage. First you need to call Calendar.getInstance() to create a calendar object.
Next you need to Set the two fields using cal.set(Calendar.HOUR, your hours) and Calendar.MINUTES the same way. Next you can call the compare function, before or after functions to get the desired info. Also you can get an instance with the current time in the current locale.
For example if you want to compare time between 11pm to 6am for calculating extra night fare for any vechicle. then following code will help you.
// Code
package com.example.timedate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.os.Bundle;
import android.app.Activity;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
Button bt;
int hour,min;
String AM_PM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
bt = (Button)findViewById(R.id.button1);
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());*/
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
int ds = c.get(Calendar.AM_PM);
if(ds==0)
AM_PM="am";
else
AM_PM="pm";
Toast.makeText(MainActivity.this, ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();
if((hour==11&&AM_PM.matches("pm")) || (hour<7&&AM_PM.matches("am")) || (hour==12&&AM_PM.matches("am")))
{
Toast.makeText(MainActivity.this, "Time is between the range", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(MainActivity.this, "Time is not between the range", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}`
As of now, I am thinking about the following approach:
int clTime = Integer.parseInt(time1.substring(0, 1))*60 + Integer.parseInt(time1.substring(3, 4));
Time now = new Time();
now.setToNow();
int nowTime = now.hour*60 + now.minute;
So, I'll need to compare just integer values clTime and nowTime.
Try this if you have specific time Zone.
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh a");
Date timeseven = dateFormat.parse("7 AM");
Date timeTen = dateFormat.parse("10 AM");
Date timeOne = dateFormat.parse("1 PM");
Date timefour = dateFormat.parse("4 PM");
Date timefive = dateFormat.parse("10 PM");
//Get current time
// Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
//Sample time
Date CurrentTime = dateFormat.parse("9 PM");
if (CurrentTime.after(timeseven) && CurrentTime.before(timeTen)) {
Toast.makeText(this, "FIRST", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeTen) && CurrentTime.before(timeOne)) {
Toast.makeText(this, "Secound", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeOne) && CurrentTime.before(timefour)) {
Toast.makeText(this, "THird", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timefour) && CurrentTime.before(timefive)) {
Toast.makeText(this, "Fourth", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not found in your time zone", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
class TimeRange {
LocalTime from;
LocalTime to;
public TimeRange(LocalTime from, LocalTime to) {
this.from = from;
this.to = to;
}
public boolean isInRange(Date givenDate) {
LocalTime givenLocalTime = getLocalDateTime(givenDate).toLocalTime();
return givenLocalTime.isAfter(from) && givenLocalTime.isBefore(to);
}
public static LocalDateTime getLocalDateTime(Date date){
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
}