HH: MM in Range Bar - java

I use Ermodo Range Bar, and the fact that I need to display a minimum value and a maximum value in hours and minutes ... That is below:
public class FilterActivity extends Activity {
private RangeBar rangebar;
final int SMALLEST_HOUR_FRACTION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filter_layout);
final TextView mDepartMin = (TextView)findViewById(R.id.tvDepartMin);
final TextView mDepartMax = (TextView)findViewById(R.id.tvDepartMax);
rangebar = (RangeBar) findViewById(R.id.rangebar1);
rangebar.setTickCount(25 * SMALLEST_HOUR_FRACTION);
rangebar.setTickHeight(0);
rangebar.setThumbRadius(8);
rangebar.setConnectingLineWeight(3);
mDepartMin.setText("" + (rangebar.getLeftIndex() / SMALLEST_HOUR_FRACTION) + ":" + SMALLEST_HOUR_FRACTION * (rangebar.getLeftIndex() % SMALLEST_HOUR_FRACTION));
mDepartMax.setText("" + (rangebar.getRightIndex() / SMALLEST_HOUR_FRACTION) + ":" + SMALLEST_HOUR_FRACTION * (rangebar.getRightIndex() % SMALLEST_HOUR_FRACTION));
rangebar.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
#Override
public void onIndexChangeListener(RangeBar rangeBar, int leftThumbIndex, int rightThumbIndex) {
int minHour = leftThumbIndex / SMALLEST_HOUR_FRACTION;
int minMinute = SMALLEST_HOUR_FRACTION * (leftThumbIndex % SMALLEST_HOUR_FRACTION);
int maxHour = rightThumbIndex / SMALLEST_HOUR_FRACTION;
int maxMinute = SMALLEST_HOUR_FRACTION * (rightThumbIndex % SMALLEST_HOUR_FRACTION);
mDepartMin.setText(minHour + ":" + minMinute);
mDepartMax.setText(maxHour + ":" + maxMinute);
}
});
}
}
Now it looks like this:
I think date or calendar class may help, but how do I use them?
I need it to be displayed as HH:MM instead of H:M

Using DecimalFormat you can achieve.
DecimalFormat deciFormat= new DecimalFormat("00");
mDepartMin.setText(deciFormat.format(minHour) + ":" + deciFormat.format(minMinute));
OR Using Calendar
mDepartMin.setText(getFormattedDate(minHour,minMinute));
Call this below method
public static String getFormattedDate(int hour, int minute) {
Calendar cale = Calendar.getInstance();
cale.set(Calendar.HOUR_OF_DAY, hour);
cale.set(Calendar.MINUTE, minute);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
return dateFormat.format(cale.getTime());
}

Related

Set date in DatePickerDialog from String

How can I set date in a DatePicker from a string (eg: 02/10/19):
Following is the code:
iqp_editDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(ActivityClass.this, (DatePickerDialog.OnDateSetListener) date1, y, m, d).show();
}
});
DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
y = year;
m = month;
d = dayOfMonth;
dateMonth = month + 1;
dateYear = year;
}
};
Update: misunderstood the question:
Calendar cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY,18);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.DATE,2);
cal.set(Calendar.MONTH,9); //Month -1
//Or to set it from a String:
String string = "02/10/19";
DateFormat format = new SimpleDateFormat("dd/MM/yy", Locale.getDefault());
Date date = format.parse(string);
cal.setTimeInMillis(date.getTime());
new DatePickerDialog(getContext(),date1, cal
.get(Calendar.YEAR), cal .get(Calendar.MONTH),
cal .get(Calendar.DAY_OF_MONTH)).show();
A string is a character array. Meaning that you could just make a loop and set the different day, month and year values to different parts of the string.
String date = "02/19/19";
String year = "";
for(int i = 0; i < date.length; i++)
{
month += date.charAt(i);
...
}
Then you'd tell it when to switch from adding to month to day to year when it encounters '/'
if(date.charAt(i) == '/')
{
...
}
at the end of it all if you need to make it into an int then do
int month = Integer.parseInt("month");
sorry I've gotta be going somewhere so I couldn't just write the code out for ya but I'm sure you can figure it out from what I gave ya.
Following code works fine for me:
new DatePickerDialog(Activityclass.this, date1, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
view.setMinDate(1559327400);
y = year;
m = month;
d = dayOfMonth;
dateMonth = month + 1;
dateYear = year;
iqp_editDate.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
try {
epoch = new java.text.SimpleDateFormat("MM/dd/yyyy").parse(m + "/" + dayOfMonth + "/" + year).getTime() / 1000;
} catch (ParseException e) {
e.printStackTrace();
}
}
};

Timer not working properly in ListView

I have used ListView to create my order cards. In which I had run a continuous timer for each card using handler to check how much time has been spent. I have used code in adapter. But my problem is when there is more then one order then the timer time overlaps on each card. For example, if I have 3 cards then ist card will show time of 1,2,3 one by one at interval of one second and 2nd will show time of 2 n 3 and for 3rd timer is stop. Another problem is timer stops after a particular amount if time. Help me regarding this.
This is my piece of code of custom adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vv = LayoutInflater.from(mContext).inflate(R.layout.adapter_listview_newpage_card,null,false);
menuModels = new ArrayList<>();
// menuModels.clear();
order_time = (TextView) vv.findViewById(R.id.order_time);
// This is my handler of timer:
final Handler myHandler = new Handler(); //declare this line in class
myHandler.postDelayed( // called this line from createlaytout function first time
new Runnable() {
public void run() {
TimeZone tz = TimeZone.getTimeZone("Asia/Kolkata");
// Log.e("TAG", "timezone "+tz );
Calendar cd = Calendar.getInstance(tz);
int min0 = cd.get(Calendar.MINUTE);
int sec0 = cd.get(Calendar.SECOND);
int hour0 = cd.get(Calendar.HOUR_OF_DAY);
// int ampm0 = cd.get(Calendar.AM_PM);
int total = (hour0 * 60 * 60) + (min0 * 60) + sec0;
int finalTime = total - Integer.parseInt(data.getTimer_time());
int hoursnew = 0;
int seconds = finalTime;
int minutes = seconds / 60;
seconds = seconds % 60;
if (minutes > 59) {
hoursnew = minutes / 60;
minutes = minutes % 60;
}
// Log.e("TAG", "timer" + minutes + "-" + seconds + "$$" + data.getOrder_id());
order_time.setText(" " + data.getOrder_id() + "&" + String.format("%02d", hoursnew) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
myHandler.postDelayed(this, 1000);
}
}, 0);
// Here order_time is textview where I add time.
}
Updated code
Hi, I was able to run timer in my code but the problem is that now i am having null pointer exception at adapter.setnotifydata change.
My code for adapter where I set time on textview
public class customadapetr_new extends BaseAdapter {
public customadapetr_new(ArrayList<DataModel> dataModels, Context context, NewPageActivity objNewPageActivity) {
this.dataSet=dataModels;
this.mContext=context;
this.objNewPageActivity = objNewPageActivity;
}
private void setTime(final int order_time, final TextView tv) {
TimeZone tz = TimeZone.getTimeZone("Asia/Kolkata");
// Log.e("TAG", "timezone "+tz );
Calendar cd = Calendar.getInstance(tz);
int min0 = cd.get(Calendar.MINUTE);
int sec0 = cd.get(Calendar.SECOND);
int hour0 = cd.get(Calendar.HOUR_OF_DAY);
// int ampm0 = cd.get(Calendar.AM_PM);
int total = (hour0 * 60 * 60) + (min0 * 60) + sec0;
int finalTime = total - order_time;
int hoursnew = 0;
int seconds = finalTime;
int minutes = seconds / 60;
seconds = seconds % 60;
if (minutes > 59) {
hoursnew = minutes / 60;
minutes = minutes % 60;
}
tv.setText(" " + String.format("%02d", hoursnew) + ":" + String.format("%02d", minutes));
}
}
And my code from where I have called handler
public class NewPageActivity extends Fragment{
private final Runnable timerRunnable = new Runnable() {
#Override
public void run() {
Log.e("TAG", "run:timer run run " );
adapter.notifyDataSetChanged();
timerHandler.postDelayed(this, 60000); //run every minute
}
};
}
I am getting error at adapter.notifyDataSetChanged() and attaching scrrenshot link of error i.e http://prntscr.com/dmxjr9

Converting date into text format

How do I convert date into its text format..for ex:if updated today..then instead of date it must show "Today",one day after it must show "Yesterday",and then after two days..it must display the date in general form(//_) on which it was updated..i tried using SimpleDateFormat..but not working..
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d= new Date();
//Convert Date object to string
String strDate = sdf.format(d);
System.out.println("Formated String is " + strDate);
d = sdf.parse("31-12-2009");
Plz help..
Thanks in advance..
Try this:
public class TimeUtils {
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static void main(String args[]) {
System.out.println(millisToLongDHMS(123));
System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
}
}
Take a look at the PrettyTime library.
You can check this Comparision of dates
import java.text.SimpleDateFormat;
import java.util.Date;
public class App {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
public static long ms, s, m, h, d, w;
static {
ms = 1;
s = ms * 1000;
m = s * 60;
h = m * 60;
d = h * 24;
w = d * 7;
}
public App() {
Date now = new Date();
Date old = new Date();
try {
old = sdf.parse("12-11-2013");
} catch (Exception e) {
e.printStackTrace();
}
long diff = now.getTime() - old.getTime();
if (diff < this.d) {
System.out.println("Today");
}
else if (diff > this.d && diff < this.d*2) {
System.out.println("Yesterday");
}
System.out.println("Difference: " + msToHms(diff));
}
public String msToHms(long ms) {
int seconds = (int) (ms / this.s) % 60 ;
int minutes = (int) ((ms / this.m) % 60);
int hours = (int) ((ms / this.h) % 24);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public static void main(String[] args) {
new App();
}
}
Output
Yesterday
Difference: 07:11:22
You have to implement your own logic based on the time difference and use the corresponding date format.
Lets assume you are getting a date from a server.
Get the device's time and compare to your date.
For your requirements there will be two cases.
The difference between the two date is less then a day, then return "Today" string.
The difference between the two date is grater then a day then use the Simple Date format to format your date as you want.
For comparing dates please see this entry: datecompare

How does cal.setTime (new Date()); work?

I want to use the cal.setTime (new Date()); in my code to update the time, but it dosent work.
import javax.swing.JOptionPane;
public class Exercise2b {
public void demo() {
String message1, message2;
int hour, minute, second;
Time dt = new Time();
hour = dt.getHour();
minute = dt.getMinute();
second = dt.getSecond();
message1 = "The clock is " + minute + " minutes over " + hour + " (+"
+ second + " seconds)";
message2 = dt.toString();
JOptionPane.showMessageDialog(null, message1);
JOptionPane.showMessageDialog(null, message2);
dt.update();
message2 = dt.toString();
JOptionPane.showMessageDialog(null, message2);
}
public static void main(String[] args) {
Exercise2b prog = new Exercise2b();
prog.demo();
}
}
import java.util.Calendar;
import java.util.Date;
public class Time {
private Calendar cal;
private int hour;
private int minute;
private int second;
public Time() {
cal = Calendar.getInstance();
this.hour = cal.get(Calendar.HOUR_OF_DAY);
this.minute = cal.get(Calendar.MINUTE);
this.second = cal.get(Calendar.SECOND);
}
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
public int getSecond() {
return this.second;
}
public String toString() {
return hour + ":" + minute + ":" + second;
}
public void update() {
cal.setTime (new Date());
}
}
I suspect the issue is that you set the cal variable but not the hour/minute/seconds variables that are set from the initial value of `cal in the constructor.
This is an example of DRY (don't repeat yourself). In this situation it's easy to get in an inconsistent state. I would simply have your accessor methods query the cal object directly (instead of using the intermediary variables). And perhaps investigate the Joda library for a better / more reliable date/time API.
The problem is that when you call the update() method you are not refreshing the values of the local variables (second/ minute / hour). Those are already initialized from the constructor.
How does cal.setTime (new Date()); work?
The javadoc states
Sets this Calendar's time with the given Date.
new Date() creates a new Date object with the millisecond value of System.currentTimeMillis().
So
cal.setTime (new Date());
will replace the internal millisecond value of cal to that of the new Date object.

Android Datepicker date add and display in single digit

i am developing an android application in which a datepicker is there to select the date of birth ... I need to display this date in a text view and this date has to be added into a single digit... and display in a textview.. i did code where the date is displyed in a textview but i need to display the total sum of it..
for example if date of birth is 04 02 1984 then 0+4 0+2 1+9+8+4 so answer is 4, 2, 4 and this has to be displayed separate in a textview.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatePicker date = (DatePicker) findViewById(R.id.datePicker1);
final TextView tvDate = (TextView) findViewById(R.id.textView2);
date.init(date.getYear(), date.getMonth(), date.getDayOfMonth(),new OnDateChangedListener()
{
#Override
public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
int sum = 0;
String date=Integer.toString(arg3);
String month=Integer.toString(arg2);
String year=Integer.toString(arg1);
tvDate.setText(month+date+year);
}
} );
}
}
CALL "sum" function for each of Day,Month and Year variables
int daySum=sum(Integer.parseInt(day));
int monthSum=sum(Integer.parseInt(month));
int yearSum=sum(Integer.parseInt(year));
tvDay.setText(daySum);
tvMonth.setText(monthSum);
tvYear.setText(yearSum);
int sum(int number){
int remainder = number % 9;
if (number == 0) {
return number;
} else {
if (remainder == 0) {
return number;
}else{
return remainder;
}
}
}
First you check the validation:
String day = "";
if (dayOfMonth < 10) {
day = "0" + dayOfMonth;
}else {
day = String.valueOf(dayOfMonth);
}
String month = "";
int get_month = monthOfYear + 1;
if (get_month < 10) {
month = "0" + get_month;
}else {
month = String.valueOf(get_month);
}
String date = day + "-" + month + "-" + year;
If i understand you correctly then what you are looking for is casting the String to ints in your onDateChanged method , so may b something like this :
int i = 0 ;
while(i<2 ) // 2 for day and month 4 for year ... or what ever fits u can also run until the length of the string
dateDigit += Integer.parseInt.subString(i++,i++);
//this is just an idea , havent tested the code or anything
keep on doing that until u have a one digit number ( Link to post for this)
or mayb some recursive method that will keep on doing that until u have only one digit
hope this fits

Categories