How to get Time Slot based on 1hour interval - java

I want to store time slot in the arraylist. i have start time and end time. based on start time it should create time slot.
For example if start time is 09:00AM and end time is 21:00PM then it should add into arraylist like below
09:00AM
10:00AM
11:00AM
12:00PM
13:00PM
14:00PM
..... so on
21:00PM
so one user books 13:00PM to 15:00PM slots so it should not be available to another user and other slot should be available. how to compare already booking time with new array list.
Code
private void getStartHourArray() {
times = new ArrayList<TimeSlot>();
Calendar calender = Calendar.getInstance();
calender.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
int ti = calender.get(Calendar.HOUR_OF_DAY);
int minutes = calender.get(Calendar.MINUTE);
System.out.println(minutes);
String[] quarterHours = {
"00",
"30",
};
boolean isflag = false;
times = new ArrayList<>();
for (int i = 9; i < 22; i++) {
if (ti > 8) {
for (int j = 0; j < 2; j++) {
if ((i == ti && minutes < Integer.parseInt(quarterHours[j])) || (i != ti) || isflag == true) {
isflag = true;
String time = i + ":" + quarterHours[j];
if (i < 10) {
time = "0" + time;
}
String hourFormat = i + ":" + quarterHours[j];
if (i < 12) {
hourFormat = time + " AM";
} else
hourFormat = time + " PM";
TimeSlot t = new TimeSlot();
t.time = hourFormat;
t.isAvailable = "Available";
times.add(t);
}
}
}
}
if (times != null) {
load.setVisibility(View.GONE);
}
}
Time Slot model class
public class TimeSlot {
public String time;
public String isAvailable;
}

Try something like this :
String firstDate = "26/02/2019";
String firstTime = "00:00 AM";
String secondDate = "26/02/2019";
String secondTime = "12:00 PM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(firstDate + " " + firstTime);
Date dateObj2 = sdf.parse(secondDate + " " + secondTime);
System.out.println("Date Start: "+dateObj1);
System.out.println("Date End: "+dateObj2);
long dif = dateObj1.getTime();
while (dif < dateObj2.getTime()) {
Date slot = new Date(dif);
System.out.println("Hour Slot --->" + slot);
dif += 3600000;
}
This will give you a time slot for each hour, add this in ArrayList and when any user select time then remove that from ArrayList and update to the server so when next
user tries to get data it won't get the first selected user time slot.

try this:
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
public class PlayGround {
private Map<LocalTime, Boolean> slots = new HashMap();
public static void main(String[] args) {
PlayGround client = new PlayGround();
client.initializeSlots();
client.allocateSlots("10:00", "13:00");
//this shouldn't be available
client.allocateSlots("11:00", "12:00");
//not sure if u want this to be available. since it is start when the 1st just finished.
client.allocateSlots("13:00", "15:00");
client.allocateSlots("16:00", "18:00");
}
private void initializeSlots() {
LocalTime time = LocalTime.of(9, 0);
slots.put(time, true);
for (int i = 1; i < 24; i++) {
slots.put(time.plusHours(i), true);
}
}
private void allocateSlots(String strTime, String edTime) {
LocalTime startTime = LocalTime.parse(strTime);
LocalTime endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
//check if the time slots between start and end time are available
if (!slots.get(startTime) || !slots.get(endTime)) {
System.out.println("slots not available" + " start time: " + strTime + " end time: " + edTime);
return;
}
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
System.out.println("slots are available" + " start time: " + strTime + " end time: " + edTime);
//then here u can mark all slots between to unavailable.
startTime = LocalTime.parse(strTime);
endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
slots.put(startTime, false);
slots.put(endTime, false);
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
}
}

Related

Get a timer with less than 60 seconds?

I`m currently trying to obtain a CountDownTimer based on the time in milliseconds of a Calendar object. The startTimer function works, so does the timerSort function. The thing is that when the timer gets initialized with the timeLeft value, it never start from a value lower than 60 seconds. This eventually causes delays bigger than 10 seconds. any suggestions?
Thank you.
Code:
private void startTimer(String x){
counter = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
updateCountdownText();
}
#Override
public void onFinish() {
timerRunning = false;
int comp = Integer.parseInt(x);
Toast.makeText(getApplicationContext(), "Alarm received!", Toast.LENGTH_LONG).show();
cal[comp].add(Calendar.MINUTE,rec[comp]);
//Update txt file
int month = cal[comp].get(Calendar.MONTH)+1;
int day = cal[comp].get(Calendar.DAY_OF_MONTH);
String data = cal[comp].get(Calendar.HOUR_OF_DAY) + ","
+cal[comp].get(Calendar.MINUTE) + ","
+day+ "," + month + ","
+cal[comp].get(Calendar.YEAR) + "," + rec[comp] + ",";
try {
FileOutputStream stream = new FileOutputStream(file[comp], false);
try {
stream.write(data.getBytes());
}catch (Exception e){
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//end update
timerSort();
BluetoothGattCharacteristic C = btper.getCharacteristic(UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"),UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"));
//If device is disconnected => it will crash
btper.writeCharacteristic(C , x.getBytes(StandardCharsets.UTF_8), WriteType.WITH_RESPONSE);
speak(String.valueOf(comp+1));
}
}.start();
}
private void updateCountdownText() {
if(counterView.getVisibility() != View.VISIBLE)
counterView.setVisibility(View.VISIBLE);
int minutes = (int)timeLeft / 1000 / 60;
int seconds = (int)timeLeft /1000 % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"Time left until next pill: %02d:%02d",minutes,seconds);
if(timeLeftFormatted.contains("00:00"))
counterView.setVisibility(View.INVISIBLE);
counterView.setText(timeLeftFormatted);
}
private void resetTimer(){}
private void timerSort(){
Context context = getApplicationContext();
int i,j;
j = 0;
int fileindex = 0;
int hour, day, month, minute, year;
calendar = Calendar.getInstance();
timeLeft = 0;
for (i = 0; i<20; i++){
fileindex = i+1;
file[i] = new File(context.getExternalFilesDir(null).getAbsolutePath(),"pills"+fileindex+".txt");
cal[i] = (Calendar) calendar.clone();
//Read text from pills file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file[i]));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String str = text.toString();
List<String> elephantList = Arrays.asList(str.split(","));
hour = Integer.parseInt(elephantList.get(0));
minute = Integer.parseInt(elephantList.get(1));
day = Integer.parseInt(elephantList.get(2));
month = Integer.parseInt(elephantList.get(3));
year = Integer.parseInt(elephantList.get(4));
rec[i] = Integer.parseInt(elephantList.get(5));
cal[i].set(Calendar.HOUR_OF_DAY, hour);
cal[i].set(Calendar.MINUTE, minute);
cal[i].set(Calendar.DAY_OF_MONTH, day);
cal[i].set(Calendar.MONTH-1, month);
cal[i].set(Calendar.YEAR,year);
}
// sorting:
int letsgo = 0;
Calendar tudor = Calendar.getInstance();
tudor.set(Calendar.YEAR,calendar.getMaximum(Calendar.YEAR));
for (i = 0; i<20; i++){
if(tudor.after(cal[i]) && cal[i].after(calendar)){
tudor = cal[i];
letsgo = i;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(letsgo), Toast.LENGTH_LONG).show();
TextView nextPillView = (TextView) findViewById(R.id.nextPillView);
if (!cal[letsgo].after(calendar)) {
nextPillView.setText("No Pills Scheduled");
} else {
// timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis() - Calendar.MILLISECOND;
int secleft = cal[letsgo].get(Calendar.SECOND)-calendar.get(Calendar.SECOND);
int minleft = cal[letsgo].get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);
timeLeft = secleft*1000 + minleft*60*1000 ;
//timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis();
String theTime = String.format(Locale.getDefault(), "%02d:%02d", cal[letsgo].get(Calendar.HOUR_OF_DAY), cal[letsgo].get(Calendar.MINUTE));
month = cal[letsgo].get(Calendar.MONTH)+1;
nextPillView.setText(cal[letsgo].get(Calendar.HOUR_OF_DAY)+":"+cal[letsgo].get(Calendar.MINUTE)+ " | | Day: " + cal[letsgo].get(Calendar.DAY_OF_MONTH) + " | | Month: " + String.valueOf(month) + " | | Year: " + cal[letsgo].get(Calendar.YEAR));
startTimer(String.valueOf(letsgo));
}
}
private void speak(String x){
float pitch = 1;
float speed = 1;
mTTS.setPitch(pitch);
mTTS.setSpeechRate(speed);
mTTS.speak("It is time to administer the compartment with the lit LED",
TextToSpeech.QUEUE_ADD,null);
}

How to set text by date and increment loop android?

I want to set text by date and incrementing loop, and when the day changes looping start from the beginning.
Example
1. day 1 =
a. nameFile 110920190001
b. nameFile 110920190002, etc.
2. day 2 =
a. nameFile 120920190001
b. nameFile 120920190002, etc.
Code
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
for(int i = 1; i <= 1000; i++) {
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
Just put the Date Initialization in the for loop for it to always take the new Instance of the date.
public static void replace(String s) {
for (int i = 1; i <= 1000; i++) {
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
}

Different time of two events in a Calendar

I've been implementing an app, and was doing a DAO class with a function, which would return all events on current day. But, I have a small bug. For example: we have 2 events - event1(02:00-03:00) and event2(14:00-16:00). And we want event1 to be the first in the row. Okay, we have implemented a sort which does it, but! event2 is 1516024800000 ms and event1 is 1542618000000.
I know that to give u a working sample would be helpful, but i am not able to...
Here is this function:
public List<Schedule> getScheduleByDate(int year, int month, int day, String Account) {
List<Schedule> schedules = new ArrayList<>();
List<CalendarClass> calendarClasses = mCalendarClassDao.getTrueCalendars();
/*if(Account.equals("ANONYMOUS")){
return schedules;
}*/
String[] INSTANCE_PROJECTION = new String[]{
CalendarContract.Instances.CALENDAR_ID, // 0
CalendarContract.Instances.TITLE, // 1
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.DTSTART,
CalendarContract.Instances.DTEND,
CalendarContract.Instances.DISPLAY_COLOR,
CalendarContract.Instances.EVENT_COLOR,
CalendarContract.Instances.EVENT_COLOR_KEY,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.OWNER_ACCOUNT,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.ORIGINAL_INSTANCE_TIME
};
Calendar startTime = Calendar.getInstance();
startTime.set(year, month, day, 0, 0, 0);
long time = startTime.getTimeInMillis();
//time -= 1000;
//end fix
Calendar endTime = Calendar.getInstance();
endTime.set(year, month, day, 23, 59, 59);
long endMillis = endTime.getTimeInMillis();
for (int i = 0; i < calendarClasses.size(); ++i) {
//String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + time + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + endTime.getTimeInMillis() + " ) AND ( " + CalendarContract.Events.CALENDAR_ID + " = " + "'" + calendarClasses.get(i).getId() + "'" + " ))";
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.READ_CALENDAR}, 1000);
}
String selection = CalendarContract.Instances.CALENDAR_ID + " = " + "'" + calendarClasses.get(i).getId() + "'";
//Cursor cursor = mContext.getContentResolver().query(CalendarContract.Events.CONTENT_URI, projection, selection, null, null);
// sort
Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, time);
ContentUris.appendId(builder, endMillis);
Cursor cursor = mContext.getContentResolver().query(builder.build(),
INSTANCE_PROJECTION,
selection,
null,
CalendarContract.Instances.DTSTART);
while (cursor.moveToNext()){
Log.wtf("1", "1");
Schedule schedule = new Schedule();
schedule.setTitle(cursor.getString(1));
schedule.setDesc(cursor.getString(2));
schedule.setTime(cursor.getLong(3));
schedule.setTime_end(cursor.getLong(4));
schedule.setColor(cursor.getInt(5));
schedule.setLocation(cursor.getString(9));
schedule.setAccount(cursor.getString(10));
schedule.setRepeat(cursor.getString(11));
schedules.add(schedule);
}
cursor.close();
}
Log.wtf("wtf", String.valueOf(schedules.size()));
if (schedules.size() > 1) {
int i = 0;
int goodPairsCounter = 0;
while (true) {
long time1 = schedules.get(i).getTime();
long time2 = schedules.get(i + 1).getTime();
Log.wtf("TIME", String.valueOf(time1) + " - " + String.valueOf(time2));
Log.wtf("TIME", schedules.get(i).getTitle() + " - " + schedules.get(i+1).getTitle());
if (time1 > time2) {
Log.wtf("TIME", "hop");
Schedule sh = new Schedule(schedules.get(i).getId(), schedules.get(i).getColor(), schedules.get(i).getTitle(), schedules.get(i).getDesc(), schedules.get(i).getLocation(), schedules.get(i).getState(), schedules.get(i).getTime(), schedules.get(i).getTime_end(), schedules.get(i).getYear(), schedules.get(i).getRepeat(), schedules.get(i).getAccount());
schedules.remove(i);
schedules.add(i + 1, sh);
goodPairsCounter = 0;
} else {
goodPairsCounter++;
}
i++;
if (i == schedules.size() - 1) {
i = 0;
}
if (goodPairsCounter == schedules.size() - 1) break;
}
}
return schedules;
}
Here is a screenshot
Need to know how to solve this problem
CLOSED. Didn't solve it yet. If you are stuck then just find another approach

Android app not responding at Calender.getInstance

I am trying to get date doing calculations. For that I'm using Calendar cal = Calendar.getInstance();I am using this import import java.util.Calendar; When the app comes to onResume I am calling a method. In that method, the first line is getting Instance(). But for some reason, I am getting this error(ANR).
at java.util.Calendar.getInstance(Calendar.java:960)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:231)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:330)
at java.util.Calendar.<init>(Calendar.java:718)
at java.util.Calendar.<init>(Calendar.java:712)
Caused by: com.github.anrwatchdog.ANRError$$$_Thread: main
Caused by: com.github.anrwatchdog.ANRError: Application Not Responding
at com.github.anrwatchdog.ANRWatchDog.void run()(SourceFile:212)
at com.splunk.mint.Mint$3.void onAppNotResponding(com.github.anrwatchdog.ANRError)(SourceFile:297)
java.lang.Exception: com.github.anrwatchdog.ANRError: Application Not Responding
EDIT (adding code as asked)
public static int getCategory(final String time) {
long thenTime = SDKUtils.getLong(getLongValue(time));
Calendar c1 = Calendar.getInstance(); // today
Calendar c2 = Calendar.getInstance();
c2.setTime(new Date(thenTime)); // your date
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return TODAY;
c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return YESTERDAY;
c1 = Calendar.getInstance();
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) )
return MONTH;
else
return YEAR;
}
public static String[] getSubTime(final String time, final int category) {
Calendar cal = Calendar.getInstance();
Date date = new Date(SDKUtils.getLong(getLongValue(time)));
TimeZone tz = TimeZone.getDefault();
cal.setTime(date);
cal.setTimeZone(tz);
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour > 12)
hour = hour - 12;
int min = cal.get(Calendar.MINUTE);
String hourStr = hour < 10 ? "0" + hour : "" + hour;
String minStr = min < 10 ? "0" + min : "" + min;
String am = cal.get(Calendar.HOUR_OF_DAY) < 12 ? " AM" : " PM";
switch (category) {
case TODAY:
case YESTERDAY: {
return new String[] { hourStr + ":" + minStr + "", am };
}
case MONTH: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
case DATE: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
default: {
String month = convertNumberToMonthMMM(cal.get(Calendar.MONTH));
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { month + " " + dateString, ", " + hourStr + ":" + minStr + "" + am };
}
}
}
These are the two methods i call. what is wrong?
Why you not try:
public class MainActivity extends AppCompatActivity
{
Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
}
}
Edit:
I think you're using:
import java.util.GregorianCalendar;
You try (add or) instead of:
import java.util.Calendar;
Regards

Error with Joda DateTime Formatter

I have a class DurationFormatter as below:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class DurationFormatter {
private final static PeriodFormatter DURATION_FORMATTER =
new PeriodFormatterBuilder().appendYears()
.appendSuffix("year", "years")
.appendSeparator(" ")
.appendMonths()
.appendSuffix("month", "months")
.appendSeparator(" ")
.appendDays()
.appendSuffix("day", "days")
.appendSeparator(" ")
.appendHours()
.appendSuffix("hour", "hours")
.appendSeparator(" ")
.appendMinutes()
.appendSuffix("minute", "minutes")
.appendSeparator(" ")
.appendSeconds()
.appendSuffix("second", "seconds")
.toFormatter();
public static String format(Date start) {
StringBuffer result = new StringBuffer();
DURATION_FORMATTER.printTo(result,
new Period(new DateTime(start), new DateTime()));
return result.toString();
}
public static String format(Date start, Date end) {
StringBuffer result = new StringBuffer();
DURATION_FORMATTER.printTo(result,
new Period(new DateTime(start),
end == null
? new DateTime()
: new DateTime(end)));
return result.toString();
}
}
And this is my Unit Test:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import junit.framework.Assert;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.junit.Test;
public class DurationFormatterTest {
#Test
public void testFormatDate() throws ParseException {
int years = 0;
int months = 0;
int weeks = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateString = "07/27/2010 12:07:34";
Date startDate = (Date) df.parse( dateString );
// Find duration 1
String duration1 = DurationFormatter.format(startDate);
// Parse duration 1 and set values into new Period
String[] tokens = duration1.split("[ ]");
for( int index = 0; index < tokens.length; index++ ) {
String token = tokens[index];
if( token.contains("years") ) {
years = Integer.valueOf(token.replace("years", ""));
System.out.println("Years are: " + years);
}
else if( token.contains("months") ) {
months = Integer.valueOf(token.replace("months", ""));
System.out.println("Months are: " + months);
}
else if( token.contains("days") ) {
days = Integer.valueOf(token.replace("days", ""));
System.out.println("Days are: " + days);
}
else if( token.contains("hours") ) {
hours = Integer.valueOf(token.replace("hours", ""));
}
else if( token.contains("minutes") ) {
minutes = Integer.valueOf(token.replace("minutes", ""));
}
else if( token.contains("seconds") ) {
seconds = Integer.valueOf(token.replace("seconds", ""));
}
}
Period period = new Period( years, months, weeks, days, hours, minutes, seconds, 0);
// User period to initialize new endDate
DateTime endDate = new DateTime(startDate).plus(period);
// Find duration 2 using new endDate
String duration2 = DurationFormatter.format(startDate, endDate.toDate());
// If the durations are the same, then success.
Assert.assertEquals(
"The date of " + duration2
+ " is equal to " + duration1,
duration1, duration2);
}
}
The result always output with error:
junit.framework.ComparisonFailure:
The date of 5days 23hours 5minutes 23seconds is equal to 1month 5days 23hours 5minutes 23seconds expected:<[1month ]5days 23hours 5minut...> but was:<[]5days 23hours 5minut...>
The string '[1month ]' always missing. Please check if I'm missing something in code?
Thanks
In your code, you have .appendSuffix("month", "months") where "month" is the singular form, "months" is the plural form.
Your test only parses the plural forms:
else if( token.contains("months") ) {
...
}
In this case, the test fails because it is only 1 month and therefore singular.
Update your testing code to parse both singular and plural form and it should work!
Documentation

Categories

Resources