Current time and range - java

I want to get the current time and compare that with time range provided by me.
for example I want to set the greeting message of Good morning if the current time is between 6:00 AM to 11:59 AM
Here is some code of my android Application
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class MainActivity extends Activity implements View.OnClickListener {
protected Calendar firstBound;
protected Calendar secondBound;
protected static Calendar cal;
protected static String timeString = null;
protected static String greetString = null;
protected static DateFormat date;
Button greetButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get a reference to the greetButton on the UI
greetButton = (Button) findViewById(R.id.greetButton);
cal = Calendar.getInstance(TimeZone.getDefault());
Date currentLocalTime = cal.getTime();
date = new SimpleDateFormat("HH:mm");
timeString = date.format(currentLocalTime);
char h1 = timeString.charAt(0);
char h2 = timeString.charAt(1);
char m1 = timeString.charAt(3);
char m2 = timeString.charAt(4);
cal.set(Calendar.HOUR,Character.getNumericValue(h1) + Character.getNumericValue(h2));
cal.set(Calendar.MINUTE,Character.getNumericValue(m1) + Character.getNumericValue(m2));
// Set the onClickListener for the greetButton to be this class.
// This requires that the class implement the View.OnClickListener callback
// the onClick() method
greetButton.setOnClickListener(this);
}
And My On Click method is
public void onClick(View v) {
TextView textMessage = (TextView) findViewById(R.id.textMessage);
EditText editFriendName = (EditText) findViewById(R.id.editFriendName);
String friendName = editFriendName.getText().toString();
switch (v.getId()) {
case R.id.greetButton:
// set the string being displayed by the TextView to the greeting
if(cal.after(setFirstBoundLimits(14, 00)) && cal.before(setSecondBoundLimits(18, 00))){
Toast.makeText(MainActivity.this, timeString, Toast.LENGTH_LONG).show();
}
// message for the friend
//textMessage.setText(getString(R.string.greetstring) + friendName + "!");
break;
default:
break;
}
}
private Calendar setFirstBoundLimits(int hh, int mm){
firstBound = Calendar.getInstance();
firstBound.set(Calendar.HOUR, hh);
firstBound.set(Calendar.MINUTE, mm);
return firstBound;
}

Period and Duration
Smart Hello
Showing Morning, afternoon, evening, night message based on Time in java
Difference in days between two dates in Java?

****Thank you...this code really worked for me
protected String getCurrentTimeMessage(){
//Date date = new Date();
Calendar cal = Calendar.getInstance();
//cal.setTime(date);
int hours = cal.get(Calendar.HOUR_OF_DAY);
if(hours>=6 && hours<=11){
//Toast.makeText(this, "Good Morning" + hours, Toast.LENGTH_SHORT).show();
return "Good Morning";
}else if(hours>=12 && hours<=16){
// Toast.makeText(this, "Good Afternoon"+ hours, Toast.LENGTH_SHORT).show();
return "Good Afternoon";
}else if(hours>=17 && hours<=20){
// Toast.makeText(this, "Good Evening"+ hours, Toast.LENGTH_SHORT).show();
return "Good Evening";
}else if(hours>=21 && hours<=23){
// Toast.makeText(this, "Good Night"+ hours, Toast.LENGTH_SHORT).show();
return "Good Night";
}
else if(hours >=0 && hours <= 5){
return "Good Night";
}
return null;
}

Related

How to retrieve value from String?

Here dob is String value . How I will get a particular value from String. Please check my code I mention there were I need it.
public class MainActivity extends AppCompatActivity {
private EditText editTextDate;
private Button mButton;
private static final String DATE_FORMAT = "dd/MM/YYYY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
btnClick();
}
private void initView() {
editTextDate = findViewById(R.id.date);
}
private void btnClick() {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String dob = editTextDate.getText().toString();
// dob is is a date like 25/05/1995
// I want to 1995 value. What will i do??
}
});
}
}
Although, you can go for splitting the string using a regex, but here, this is what you need to learn. SimpleDateFormat. This will give you a lot more control especially when you'll use time with it.
Java
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date yourDate = format.parse("25/05/1995");
Calendar yourCal = new Calendar.getInstance();
yourCal.setTime(yourDate);
Log.d("Tag","Day : "+ yourCal.get(Calendar.DAY_OF_MONTH));
Log.d("Tag","Month: " + yourCal.get(Calendar.MONTH) + 1);
Log.d("Tag","Year: " + yourCal.get(Calendar.YEAR));
Kotlin
val format = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val yourDate = format.parse("25/05/1995")
val yourCal: Calendar = Calendar.getInstance()
yourCal.time = yourDate!!
Log.d("Tag", "Day : " + yourCal[Calendar.DAY_OF_MONTH])
Log.d("Tag", "Month: " + yourCal.get(Calendar.MONTH) + 1)
Log.d("Tag", "Year: " + yourCal.get(Calendar.YEAR))
Remember, month starts from 0 for January so you've to +1 in that, And capital 'M' denotes month in java where as small 'm' denotes minutes. There are lots of formats for SimpleDateFormat, you can use any of them.
Just use the appropriate function.
String#split()
String dob = editTextDate.getText().split("/")[2]

how to compare date and not display feauter week date in android

public class TestActvity extends AppCompatActivity implements View.OnClickListener {
Button next;
Button previous;
TextView textView;
int interval = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(this);
previous.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
getDate(interval);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.next)
{
interval = interval + 7;
getDate(interval);
} else if (view.getId() == R.id.previous) {
interval = interval - 7;
getDate(interval);
}
}
public void getDate(int interval) {
try {
Calendar c = GregorianCalendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DAY_OF_WEEK, interval - 2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
textView.setText(startDate + " to " + endDate);
Date date = new Date();
String modifiedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
if ( endDate.compareTo(modifiedDate) > 0) {
Log.d("data", "" + "");
}
Log.d("data", "" + "");
} catch (Exception e) {
}
}
}
Using this code, i am displaying Monday to Sunday like
2017-7-3 to 2017-7-9 ,2017-7-10 to 2017-7-16 ,2017-7-17 to 2017-7-23
,2017-7-24 to 2017-7-30 ,2017-7-31 to 2017-8-5 ...
Receptively but what I want, if current week is
2017-7-24 to 2017-7-30
then when we click on next week it should display it should display only previous week please suggest me in this scenario I will compare date.
if (c.getTime().after(new Date())){
next.setVisibility(View.GONE);
}else {
next.setVisibility(View.VISIBLE);
}
apply this Condition and enjoy !!

Get 12 hour time from DateTime picker

I am using Material DateTime picker for choosing date and time. Its working fine, but in onTimeSetListener method it returns hourOfTheDay in 24 hours format.
I want to show it it 12 hour format for that I used the if condition where hours are greater than 12 then it should show PM, but the hour number dose not change.
How can I change this?
public class TransportFragment extends Fragment implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener {
private OnFragmentInteractionListener mListener;
private EditText mEditTxt_From,mEditTxt_To,mEditTxt_DateTime;
int PLACE_PICKER_REQUEST = 1;
private static final String TAG = "PlacePickerSample";
private static final int REQUEST_PLACE_PICKER_FROM = 1;
private static final int REQUEST_PLACE_PICKER_TO = 2;
private String mDate;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_transport, container, false);
mEditTxt_From = (EditText) view.findViewById(R.id.editTextFrom);
mEditTxt_To = (EditText) view.findViewById(R.id.editTextTo);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setVersion(DatePickerDialog.Version.VERSION_2);
dpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
dpd.show(getFragmentManager(), "Datepickerdialog");
}
});
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
mDate = dayOfMonth+"/"+(++monthOfYear)+"/"+year;
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
false
);
tpd.setVersion(TimePickerDialog.Version.VERSION_2);
tpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
Log.d("TimePicker", "Dialog was cancelled");
}
});
tpd.show(getFragmentManager(), "Timepickerdialog");
}
#Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
String minuteString = minute < 10 ? "0"+minute : ""+minute;
String secondString = second < 10 ? "0"+second : ""+second;
String time;
if(hourOfDay > 12)
{
time = hourOfDay + ":" + minuteString + " PM";
}
else {
time = hourOfDay + ":" + minuteString + " AM";
}
mEditTxt_DateTime.setText(mDate + " " + time );
}
}
Please help. Thank you.
I think your if statement is invalid:
if (hourOfDay > 12) {
time = (hourOfDay - 12) + ":" + minuteString + " PM";
} else {
...
}
You do not need to reinvent the wheel. In particular, if your app is working with dates and times, you should consider getting the ThreeTenABP library and using the modern Java date and time classes. One of these, LocalTime, solves your task in two lines:
DateTimeFormatter twelveHourTimeFormatter
= DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
String time = LocalTime.of(hourOfDay, minute, second)
.format(twelveHourTimeFormatter);
Once you move to Java 8 the classes are built-in and you can discard the library.
In case you don’t want the dependency on one more external library, you can obtain the same with the outdated classes GregorianCalendar, Date and SimpleDateFormat, only it will be less elegant and far from future-proof.
Links
ThreeTenABP
Question: How to use ThreeTenABP in Android Project

Error in Android Edittext Onclick Datepickerdialog in lollipop

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

How to compare current time with time range?

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());
}
}

Categories