how to use setSelection on dateRangePicker of material-component? - java

I want to display a selected dates range when open the dateRangePicker, I knew the method setSelected is for this and I tried it its not work, or maybe am doing something wrong, please help
here what I tried already
public void openDateRangePicker(View view) {
MaterialDatePicker.Builder builder =
MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
MaterialDatePicker<Pair<Long,Long>> picker = builder.build();
builder.setCalendarConstraints(constraintsBuilder.build());
picker.setStyle(DialogFragment.STYLE_NORMAL, R.style.Custom_MaterialCalendar_Fullscreen);
if(!firstDateStr.isEmpty() || !endDateStr.isEmpty()){
builder.setSelection(selectionDates);
}
picker.show(getSupportFragmentManager(), picker.toString());
picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
#Override
public void onPositiveButtonClick(Pair<Long, Long> selection) {
long firstDateLong = selection.first;
Date firstDate=new Date(firstDateLong);
long endDateLong = selection.second;
Date endDate=new Date(endDateLong);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
//format yyyy-MM-dd
firstDateStr = sdf2.format(firstDate);
endDateStr = sdf2.format(endDate);
selectionDates = selection;
selectedDatesStr = firstDateStr + " to " + endDateStr ;//+ " (" + (daysBetween + 1) + " days)";
tvDates.setText(selectedDatesStr);
tvDates.setTypeface(Typeface.DEFAULT_BOLD);
picker.dismiss();
}
});
}
what I did here is save the selection object and use it to show the range when open the picker next time, but it opens without any selection like it open for the first time!

order of your lines matters,you need to call builder.build(); after finishing setting up the builder.
String firstDateStr="";
String endDateStr="";
Pair<Long, Long> selectionDates=null;
public void openDateRangePicker() {
MaterialDatePicker.Builder builder =
MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
builder.setCalendarConstraints(constraintsBuilder.build());
// picker.setStyle(DialogFragment.STYLE_NORMAL);
if(selectionDates!=null){
builder.setSelection(selectionDates);
}
MaterialDatePicker<Pair<Long,Long>> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());
picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
#Override
public void onPositiveButtonClick(Pair<Long, Long> selection) {
long firstDateLong = selection.first;
Date firstDate=new Date(firstDateLong);
long endDateLong = selection.second;
Date endDate=new Date(endDateLong);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
//format yyyy-MM-dd
firstDateStr = sdf2.format(firstDate);
endDateStr = sdf2.format(endDate);
selectionDates = selection;
selectedDatesStr = firstDateStr + " to " + endDateStr ;//+ " (" + (daysBetween + 1) + " days)";
tvDates.setText(selectedDatesStr);
tvDates.setTypeface(Typeface.DEFAULT_BOLD);
picker.dismiss();
}
});
}

Related

Replicate column Header

I Guys, when I enter more than one store, the header columns are duplicated(if the store are two, if store are three the header colums triplicate). Example: if I choose two stores you create two headers (the duplicate header does not have rows). I leave you the code in case you can help me I would be very grateful.
deliveringGrid.getChildren().clear();
Date startDate = dateFrom.getValue();
Date endDate = dateTo.getValue();
List<Date> dates = new ArrayList<Date>();
long start = startDate.getTime();
long end = endDate.getTime();
long interval = 24 * 1000 * 60 * 60;
while (start <= end)
{
dates.add(new Date(start));
start += interval;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
columns = new Columns();
columns.setStyle("text-align: center;");
rows = new Rows();
Column col = new Column();
col.setStyle("width: 120px; background: rgb(195,218,249);");
Label label = new Label(getLabel(STORE).toUpperCase());
label.setStyle("color: rgb(21,66,151); font-weight: bold;");
col.appendChild(label);
columns.appendChild(col);
for (StoreManagerModel storeManagerModel : storeList)
{
Row storeRow = new Row();
storeRow.setStyle("text-align: center;");
Label storeName = new Label(storeManagerModel.getName() + " - " + storeManagerModel.getStoreRef());
storeName.setStyle("color: rgb(21,66,151); font-weight: bold;");
storeRow.appendChild(storeName);
for (Date date : dates)
{
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
List<List<Object>> query = orderDeliveringService.getOrderDeliveringWithDayDistribution(date, storeManagerModel);
List<OrderDeliveringModel> orderDeliveringModelList = OrderDeliveringConverter.convertData(query);
Column dayCol = new Column();
dayCol.setStyle(COLUMN_HEADERS_STYLE);
int dayOfWeek = TimeSlotDateUtils.getDayOfWeek(date);
String dayString = getDayOfWeekAsString(dayOfWeek);
Label headerLabel = new Label(dayString + " " + dateFormat.format(date));
dayCol.appendChild(headerLabel);
Label day1;
if (CollectionUtils.isNotEmpty(orderDeliveringModelList))
{
StoreManagerModel orderDeliveringModelStore = orderDeliveringModelList.get(0).getStore();
Date orderDeliveringModelData = orderDeliveringModelList.get(0).getDay();
Integer orderDeliveringModelOrder = orderDeliveringModelList.get(0).getOrderCount().get(0);
Integer orderDeliveringModelTotalCapacity = orderDeliveringModelList.get(0).getTotalCapacity().get(0);
day1 = new Label(orderDeliveringModelOrder + " / " + orderDeliveringModelTotalCapacity);
day1.setAttribute("storePlusDate", orderDeliveringModelStore.getStoreRef() + "*" + dateFormat.format(date));
}
else
{
day1 = new Label(" - / - ");
day1.setAttribute("storePlusDate", storeManagerModel.getStoreRef() + "*" + dateFormat.format(date));
}
columns.appendChild(dayCol);
storeRow.appendChild(day1);
}
rows.appendChild(storeRow);
}
deliveringGrid.appendChild(columns);
deliveringGrid.appendChild(rows);

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

How to make the format 2015-09-04T11:30:06-0500 to 2015-09-04T11:30:06-05:00 in SimpleDateFormat

Used the below code and not getting the exact output.
Desired output:
2015-09-04T11:30:06-0500 to 2015-09-04T11:30:06-05:00
Actual output:
dateValue => 2015-10-19T16:52:23-0400
a => 2015-10-20T02:22:23+0530
My code:
public class test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = formattedDate("2015-10-19T16:52:23-0400");
System.out.println ("a => " + a);
}
public static String formattedDate (String dateValue) {
String expectedFormat = "";
SimpleDateFormat inputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat outputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
try {
System.out.println("dateValue => " + dateValue);
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(true);
Date d = inputDateFormat.parse(dateValue);
expectedFormat = outputDateFormat.format(d);
} catch (Exception e) {
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
expectedFormat = outputDateFormat.format(cal.getTime());
}
return expectedFormat;
}
}
Under Java 7 and higher, you can use XXX to output the time zone with a column:
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
When you use this to format a data, it will return for example:
2001-07-04T12:08:56-07:00
See the documentation for more examples.
Since I'm using 1.6, XXX is not supported. So used alternative way to achieve this. This is what I did for alternative way..
public static String formattedDate (String dateValue) {
StringBuilder expectedFormat;
SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(false);
Date d = inputDateFormat.parse(dateValue);
} catch (Exception e) {
System.out.println("Error in parsing : " + e.getMessage());
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
dateValue = inputDateFormat.format(cal.getTime());
} finally {
expectedFormat = new StringBuilder(dateValue).insert(dateValue.length()-2, ":");
}
return expectedFormat.toString();
}
When you need only the third last character changed and give a string as a parameter how about leaving it a String?
public static String formattedDate (String dateValue)
{
return dateValue.substring(0, dateValue.length() - 2)
+ ":"
+ dateValue.substring(dateValue.length() - 2);
}
Output:
a => 2015-10-19T16:52:23-04:00

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.

How to itrate the json list?

I have a list,that list i have put inside the json object that list I want to iterate using jquery and I need to append to the table.Could anyone please help me to solve this.
This is my action class.
String startdate = request.getParameter("startdate");
String endate = request.getParameter("endate");
String leavepolicyid = request.getParameter("leavepolicyid");
Session session = HibernateUtil.getSessionFactory().openSession();
LeavePolicyEntity lpe = (LeavePolicyEntity) session.get(LeavePolicyEntity.class, Integer.parseInt(leavepolicyid));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar fromcal = Calendar.getInstance();
fromcal.setTime(sdf.parse(startdate));
Calendar endCal = Calendar.getInstance();
endCal.setTime(sdf.parse(endate));
int actualDays = 0;
boolean excludeWeekends = lpe.isExcludeweekends();
int totalDays = 0;
List daysList = new ArrayList();
StringBuffer sb = new StringBuffer();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE", Locale.US);
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy");
while (!fromcal.after(endCal)) {
sb.setLength(0);
System.out.println("fromcal.get(Calendar.DAY_OF_WEEK)" + fromcal.get(Calendar.DAY_OF_WEEK));
if (excludeWeekends) {
if ((7 != fromcal.get(Calendar.DAY_OF_WEEK)) && (1 != fromcal.get(Calendar.DAY_OF_WEEK))) {
actualDays++;
// String asWeek = dateFormat.format(fromcal.getTime());
sb.append(dateFormat.format(fromcal.getTime()) + "-" + sdf1.format(fromcal.getTime()) + ",true");
} else {
sb.append(dateFormat.format(fromcal.getTime()) + "-" + sdf1.format(fromcal.getTime()) + ",false");
}
} else {
sb.append(dateFormat.format(fromcal.getTime()) + "-" + sdf1.format(fromcal.getTime()) + ",true");
actualDays++;
}
daysList.add(sb.toString());
fromcal.add(Calendar.DATE, 1);
totalDays++;
}
// System.out.println("daysListdaysListdaysList" + daysList);
// JSONObject json = new JSONObject();
// json.accumulate("weekdays", daysList);
response.setContentType("application/json");
String json = new Gson().toJson(daysList);
System.out.println("Json" + json);
response.getWriter().print(json);
Jquery ajax
$("[id^='leavetype']").change(function() {
var startdate = $('#leavetypefromdate').val();
var enddate = $('#leavetypetodate').val();
// alert(startdate)
// alert(enddate)
if (startdate != "" && enddate != "") {
if (new Date(startdate) <= new Date(enddate)) {
$.get("leaverequestvalidation.do?method=validateleavetype", {startdate: startdate, endate: enddate, leavepolicyid: $('#leaveTypeid').val()}, function(responce) {
alert(responce);
$.each(JSON.parse(responce), function(idx, obj) {
alert(1);
});
});
} else {
alert("FromDate Cannot Be Greater Than ToDate")
}
}
});

Categories

Resources