How to set text by date and increment loop android? - java

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

Related

How to get Time Slot based on 1hour interval

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

For loop not looping through all data

The For Loop is not looping in my codes through all my data. I've read through it thoroughly and still couldn't find any error.
Hope its not some stupid mistake.
Here's a snippet of my for loop codes:
String convertedDuration= "";
String timeConverted = convertedDuration;
for (int i = 0; i < submissionTime.length; i ++)
{
String strDate = submissionTime[i];
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date getDate = sdf.parse(strDate);
getDate.getTime();
convertedDuration = timeConverted + (getDate.getTime());
}
System.out.println("convertedDuration : "+ convertedDuration);
thanks for any help in advance :)
print inside your loop not outside .your are only print last one.move print line to loop.
for (int i = 0; i < submissionTime.length; i ++)
{
String strDate = submissionTime[i];
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date getDate = sdf.parse(strDate);
getDate.getTime();
convertedDuration = timeConverted + (getDate.getTime());
System.out.println("convertedDuration : "+ convertedDuration);
}

Java set the tommorrow id number to one

My requirements:
ddmm + 2numbers
dd - day
mm - month
number - id number
Examples of my output
Today - 031201, 031202, 031203 ...
Tommorrow - 041201
Properties file: (idNumber.properties)
idNumber = 1;
Here is the java code I did:
public class Test{
public static void main(String[] args)
{
Test test = new Test();
test.generate();
}
public String generate()
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber();
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(){
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
My question is how do I reset the tommorrow id number start from 01?
You can add a property LAST_VISIT to your properties file. When you want to save the properties file, set the current date to it. In this way
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
idNoProp.setProperty("LAST_VISIT", currentDate);
Now in generateIdNumber() first check the value of LAST_VISIT. If it dose not equal currentDate , you must reset idNo. It works for everyday and every tommorow.
Try to put a class static field to remember last used date for ids. Whenever you are in the next date relatively to the field you'll reset your idNo and update the last used date field (sorry for spelling)
You can store a Map<String,Integer> that would hold the last index for each String representation of date. This way, each date would have its own indices starting with 1.
You can run a scheduler which will reset the idNo at the start of each day, like at 00 hours. This will always gives you the consistent result, as if sometimes server/program restarts, it will not lead to any duplicate result.
if you want format a number with two number, example '01' you could do this:
String.format("%02d", Integer.valueOf(idNumber));
instead of:
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
public class Test{
public static void main(String[] args) throws IOException
{
Test test = new Test();
System.out.println(""+test.generate());
}
public String generate() throws IOException
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber(currentDate);
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(String currentDate) throws IOException{
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String strOnlyDay = currentDate.substring(0, 2);
System.out.println(strOnlyDay);// will return the first two characters of the day
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
if (strOnlyDay.equals("01")){
idNo = 1;
}
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
Try to pass the value of your current date into generateIdNumber than see the code. I hope this will help. Hoping you will preserve the value of idNo.

Convert the string "8:00" into the minutes (integer value)

I'm reading the data from CSV file. One of the fields is the time in the format H:mm, i.e. "8:00". How to convert this string value into the minutes (integer value), i.e. 8:00 = 8*60 = 480 minutes?
String csvFilename = "test.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
csvReader.readNext(); // to skip the headers
int i = 0;
while((row = csvReader.readNext()) != null) {
int open = Integer.parseInt(row[0]);
}
csvReader.close();
You can use java.text.SimpleDateFormat to convert String to Date. And then java.util.Calendar to extract hours and minutes.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse("8:00");
cal.setTime(date);
int mins = cal.get(Calendar.HOUR)*60 + cal.get(Calendar.MINUTE);
Try something like this
String str = "8:10";
int minutes=0;
String[] arr= str.split(":");
if(arr.length==2){
minutes=Integer.parseInt(arr[0])*60+Integer.parseInt(arr[1]);
}
System.out.println(minutes);
Write something like this to convert into int
public int convertToMin(String hrmin) {
String[] tokens = hrmin.split(":");
int minutes = 0;
for (int i = tokens.length; i > 0; i--) {
int value = Integer.parseInt(tokens[i - 1]);
if (i == 1) {
minutes += 60 * value;
}
else {
minutes += value;
}
}
return minutes;
}
Try this
String str = "8:20";
int ans = (Integer.parseInt(str.split(":")[0])* 60)+Integer.parseInt(str.split(":")[1]);
System.out.println("Answer = "+ans);

Iterating through current month to get all events

I have a calendar app. I want to add a listview which displays all the events for the current month.
This is the code which I am using to loop but it displays only the last event of the month, instead of ALL the events:
for(int i = 0; i < _calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++){
if(isHoliday(i, month, year, date_value))
{
String date= i + " " + getMonthForInt(month);
CalendarEvents events = new CalendarEvents();
final ArrayList<Event> e = new ArrayList<Event>();
e.addAll(events.eventDetails(hijri_date[1], hijri_date[0]));
for (int j = 0; j < e.size(); j++)
{
Event event = e.get(j);
summary_data = new Summary[]
{
new Summary(date, event.eventdetails)
};
}
}
}
summaryAdapter = new SummaryAdapter(this.getActivity().getApplicationContext(), R.layout.listview_item_row, summary_data);
calendarSummary = (ListView) v.findViewById(R.id.calendarSummary);
calendarSummary.setAdapter(summaryAdapter);
UPDATED CODE:
CalendarEvents events = new CalendarEvents();
final ArrayList<Event> e = new ArrayList<Event>();
String date;
for(int i = 0; i < _calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++){
if(isHoliday(i, month, year, date_value))
{
date = i + "-" + month + "-" + year;
e.addAll(events.eventDetails(month, day));
summary_data = new Summary[e.size()];
for (int j = 0; j < e.size(); j++)
{
Event event = e.get(j);
summary_data[j] = new Summary(date, event.eventdetails);
}
}
}
You are creating array every time and assigning to same reference. That is why last one replacing everything else.
summary_data = new Summary[]
{
new Summary(date, event.eventdetails)
};
You know the size ahead, so create array with size first and then assign values to index
summary_data = new Summary[e.size()];
for(....)
{
......
summary_data[j] = new Summary(date, event.eventdetails);
}
/////
if(isHoliday(i, month, year, date_value))
{
String date = i + "-" + month + "-" + year;

Categories

Resources