I'm using custom wheel time picker I want to set start time of the day in timepicker and End time of the day in timepicker
''''private void openTimePickerDialog(boolean is24r) {
Calendar calendar = Calendar.getInstance();
_timePickerDialog = new TimePickerDialog(
context,
AlertDialog.THEME_HOLO_LIGHT,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24r);
_timePickerDialog.setTitle("Set Alarm");
_timePickerDialog.show();
}''''
'''' TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
txtsetremindme.setText("before :Not Set");
int hours = hourOfDay;
int minutes = minute;
alarmhour = hourOfDay;
alarmminutes = minutes;
String am_pm = "";
//To get the AM/PM value set by user
if (hours > 12) {
hours -= 12;
am_pm = "PM";
} else if (hours == 0) {
hours += 12;
am_pm = "AM";
} else if (hours == 12) {
am_pm = "PM";
} else {
am_pm = "AM";
}
String min = "";
if (minutes < 10)
min = "0" + minutes;
else
min = String.valueOf(minutes);
String hrs = "";
if (hours < 10)
hrs = "0" + hours;
else
hrs = String.valueOf(hours);
// Append in a StringBuilder to show setTime at the time of alarm ring
setTime = new StringBuilder().append(hrs).append(":")
.append(min).append(" ").append(am_pm).toString();
AMPM = am_pm.toString();
SimpleDateFormat format = new SimpleDateFormat("HH:mm a");
try {
Selectedtime = format.parse(setTime);
setDimensions(cardsetrepeat, MATCH_PARENT, MATCH_PARENT);
setDimensions(cardsetremindmebefore, MATCH_PARENT, MATCH_PARENT);
} catch (Exception e) {
}
Settime.setText(setTime);
//Getting the time difference of current time and time set by user
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if (calSet.compareTo(calNow) <= 0) { //If time set by user is already passed, set it for next day
calSet.add(Calendar.DATE, 1);
}
}
};''''
Related
Actually, I am frustrated because after so many tries I haven't got any success in getting time from the textview and show it in the TimePickerDialog.
Whenever I click on the layout to get the TimePickerDialog, it always shows 12:00 AM.
I want when I click on this and timepicker will show this time which is on the image.
Here is my code:
public void a(final TextView txv){
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
datetime = Calendar.getInstance();
currentHour=datetime.get(Calendar.HOUR_OF_DAY);
currentMinute=datetime.get(Calendar.MINUTE);
int hour = hourOfDay % 12;
if (hour == 0)
hour = 12;
String strHrsToShow = (String.format("%02d:%02d %s", hour == 0 ? 12 : hour, minute, hourOfDay < 12 ? "AM" : "PM"));
finalTime = strHrsToShow;
if (txv.equals(wakeUpTime)) {
wakeUpTime.setText(finalTime);
}
editor.commit();
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
Initialise currentHour, currentMinute to avoid default 12:00 AM.
currentHour = 12;
currentMinute = 34;
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
... omitted...
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
After creating object for TimePickerDialog "thetimePickerDialog",
use:
timePickerDialog.update(int hourOfDay, int minuteOfHour);
Which in your case will be :
timePickerDialog.update(currentHour,currentMinute);
How to disable only sunday in the following code?
We cannot find any solution to disable sunday for a month
MainActivity.java:
CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
Calendar calendar = Calendar.getInstance();
calendarView.setMinDate(calendar.getTimeInMillis());
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener()
{
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Toast.makeText(getApplicationContext(), "" + dayOfMonth, 0).show();// TODO Auto-generated method stub`enter code here`
}
});
I have used this code in a project. See if it produces desirable result -
//Global Variables
private Calendar lastSelectedCalendar = null;
private CalendarView calendarView;
//
calendarView = (CalendarView) findViewById(R.id.calendarView);
lastSelectedCalendar = Calendar.getInstance();
calendarView.setMinDate(lastSelectedCalendar.getTimeInMillis() - 1000);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Calendar checkCalendar = Calendar.getInstance();
checkCalendar.set(year, month, dayOfMonth);
if(checkCalendar.equals(lastSelectedCalendar))
return;
if(checkCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
calendarView.setDate(lastSelectedCalendar.getTimeInMillis());
else
lastSelectedCalendar = checkCalendar;
}
});
Calendar sunday;
List<Calendar> weekends = new ArrayList<>();
int weeks = 5;
for (int i = 0; i < (weeks * 7) ; i = i + 7) {
sunday = Calendar.getInstance();
sunday.add(Calendar.DAY_OF_YEAR, (Calendar.SUNDAY - sunday.get(Calendar.DAY_OF_WEEK) + 7 + i));
// saturday = Calendar.getInstance();
// saturday.add(Calendar.DAY_OF_YEAR, (Calendar.SATURDAY - saturday.get(Calendar.DAY_OF_WEEK) + i));
// weekends.add(saturday);
weekends.add(sunday);
}
Calendar[] disabledDays = weekends.toArray(new Calendar[weekends.size()]);
dpd.setDisabledDays(disabledDays);
This code disables the next 5 Sundays, if you wish to do it for a longer period, just need to modify week. If you wish to disable Saturdays too, just uncomment those lines.
If you want to do it for previous 5 Sundays then, just modify the for loop to:
for (int i = 0; i < (weeks * 7); i = i + 7) {
for(int j =0; j > (weeks*7) ; j = j - 7);
sunday = Calendar.getInstance();
sunday.add(Calendar.DAY_OF_YEAR, (Calendar.SUNDAY - sunday.get(Calendar.DAY_OF_WEEK) + 7 + i));
// saturday = Calendar.getInstance();
// saturday.add(Calendar.DAY_OF_YEAR, (Calendar.SATURDAY - saturday.get(Calendar.DAY_OF_WEEK) + i));
// weekends.add(saturday);
weekends.add(sunday);
}
I have a given date, with the format dd. MMMM yyyy HH:mm 'Uhr'
Now I want to check this date with the current date, checking if its in the scope of +1 hour and -1 hour of the current date time, when its in this scope, the if condition should be statisfied.
I would appreciate it, when someone could help me!
Btw, I have no opportunity to use JODA.
Eric posted in another answer: Here's the link for credit. A rather simple method that get's the time apart using the Calendar class. If anything you can pick it apart to learn a bit about getting the differences between two times.
public static int hoursAgo(String datetime) {
Calendar date = Calendar.getInstance();
date.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime)); // Parse into Date object
Calendar now = Calendar.getInstance(); // Get time now
long differenceInMillis = now.getTimeInMillis() - date.getTimeInMillis();
long differenceInHours = (differenceInMillis) / 1000L / 60L / 60L; // Divide by millis/sec, secs/min, mins/hr
return (int)differenceInHours;
}
DateFormat format = new SimpleDateFormat("dd. MM yyyy HH:mm");
String dateString= "16. 10 2015 11:05";
Date date = format.parse(dateString);
private static boolean DateInScope(Date date) {
Date currentTime = new Date();
long hours = TimeUnit.MILLISECONDS.toHours(currentTime.getTime());
long hours2 = TimeUnit.MILLISECONDS.toHours(date.getTime());
return hours - 1 == hours2 || hours + 1 == hours2;
}
May be the following method could help you.
public static String getDiffBtwnDates(Date date1, Date date2){
long date1InMillis = date1.getTime();
long date2InMillis;
if (date2==null){
date2InMillis = System.currentTimeMillis();
}else{
date2InMillis = date2.getTime();
}
long dateDiffInMillis = date2InMillis-date1InMillis;
StringBuffer sTimeSince = new StringBuffer("");
if(dateDiffInMillis > YEAR){
if(dateDiffInMillis/YEAR>1){
sTimeSince.append(dateDiffInMillis / YEAR).append(" Years ");
dateDiffInMillis %= YEAR;
}else {
sTimeSince.append(dateDiffInMillis / YEAR).append(" Year ");
dateDiffInMillis %= YEAR;
}
}
if (dateDiffInMillis > DAY) {
if(dateDiffInMillis/DAY > 1){
sTimeSince.append(dateDiffInMillis / DAY).append(" Days ");
dateDiffInMillis %= DAY;
}else {
sTimeSince.append(dateDiffInMillis / DAY).append(" Day ");
dateDiffInMillis %= DAY;
}
}
if (dateDiffInMillis > HOUR) {
if(dateDiffInMillis/HOUR>1){
sTimeSince.append(dateDiffInMillis / HOUR).append(" Hrs ");
dateDiffInMillis %= HOUR;
}else{
sTimeSince.append(dateDiffInMillis / HOUR).append(" Hr ");
dateDiffInMillis %= HOUR;
}
}
if (dateDiffInMillis > MINUTE) {
if (dateDiffInMillis / MINUTE > 1) {
sTimeSince.append(dateDiffInMillis / MINUTE).append(" Mins ");
dateDiffInMillis %= MINUTE;
} else {
sTimeSince.append(dateDiffInMillis / MINUTE).append(" Min ");
dateDiffInMillis %= MINUTE;
}
}
if (dateDiffInMillis > SECOND) {
sTimeSince.append(dateDiffInMillis / SECOND).append(" Sec ");
dateDiffInMillis %= SECOND;
}
sTimeSince.append(dateDiffInMillis + " ms");
sTimeSince.toString();
return sTimeSince.toString();
}
Here is a very simple method that does the exact comparison you need, i did some tests and it seems to work:
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class TestDateDiff {
public static void main(String[] args) throws Exception {
if (isWhitinOneHOur("16. October 2015 16:30")) {
System.out.println("Date OK");
} else {
System.out.println("Date KO");
}
}
public static boolean isWhitinOneHOur(String dateAsStr) throws Exception {
SimpleDateFormat sdf= new SimpleDateFormat("dd. MMMM yyyy HH:mm", Locale.US);
Date date=sdf.parse(dateAsStr);
Date now=new Date();
long oneHour=1000*60*60;
if ((now.getTime()+oneHour)>=date.getTime() && (now.getTime()-oneHour)<=date.getTime()) {
return true;
} else {
return false;
}
}
}
UPDATE
I am creating a pregnancy due date countdown, so I use android.widget.DatePicker as a tool to set the due date.
For example:
the set due date is Jan. 9 2015
the date now is Nov. 9 2014
so the left months, days and weeks is 2 months, 62 days and 8weeks
So far i can only display the set due date.
Question:
How to get the exact months weeks and days left when the user set the due date.
UPDATE CODE
Here's the code:
private TextView txtResultDueDate ;
private DatePicker datePicker;
private Calendar calendar;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
txtResultDueDate = (TextView) findViewById(R.id.txtDue);
btnChangeDate = (Button)findViewById(R.id.button1);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
Chronology chrono = GregorianChronology.getInstance();
DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);
DateTime current = new DateTime();
Interval interval = new Interval(current.toInstant(), end.toInstant());
Period duePeriod = interval.toPeriod();
showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());
}
};
private void showDate(int year, int month, int day) {
txtResultDueDate.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
This is the error that I encounter when I set the due date using DatePicker:
FATAL EXCEPTION: main
java.lang.IllegalArgumentException: The end instant must be greater orequal to the start
at org.joda.time.base.Abstraction.checkInterval(AbstractInterval.java.63)
at org.joda.time.base.BaseInterval(BaseInterval.java:94)
at org.joda.time.Interval.(Interval.java.122)
at com.date.androin.Profile$1.onDataset(Profile.java:168)
at android.app.DatePickerDialog.tryNotifyDataSet(DatePickerDialog.java.148)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java.116)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStrat.main(Native Method)
There is a library Joda Time. It is better the Date API provided by Java
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
Yes, you can use joda lib with android DatePicker
Chronology chrono = GregorianChronology.getInstance();
// end datetime
DateTime end = new DateTime(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 0, 0 ,chrono);
// current datetime
DateTime current = new DateTime();
Then instantiate Interval with start and end datetime
Interval interval = new Interval(current.toInstant(), end.toInstant());
then use the Interval api to get the Period from which you can extract the difference of months/days/weeks
Period duePeriod = interval.toPeriod();
// get difference in months
duePeriod.getMonths();
// get difference in weeks
duePeriod.getWeeks();
PLease refer the below Javadoc of Period for complete list of API
http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html
For Android, in your case add the above code into your DatePicker onDateSet listener. finally the listener method would like this,
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
// TODO Auto-generated method stub
Chronology chrono = GregorianChronology.getInstance();
// end datetime
DateTime end = new DateTime(arg0.getYear(), arg0.getMonth(), arg0.getDayOfMonth(), 0, 0, chrono);
// current datetime
DateTime current = new DateTime();
Interval interval = new Interval(current.toInstant(), end.toInstant());
Period duePeriod = interval.toPeriod();
showDate(duePeriod.getYears(), duePeriod.getMonths(), duePeriod.getDays());
}
//somewhere in your code, init part
Calendar then = setDate(9, 0, 2015);//9 january 2015
Calendar c = Calendar.getInstance();
Calendar now = setDate(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
String leftDays = getLeftDays(then, now);//your result
//method setting days months years - we ignore hours and minutes
private String getLeftDays(Calendar then, Calendar now) {
long leftMilis = then.getTimeInMillis() - now.getTimeInMillis();
int seconds = (int) (leftMilis / 1000);
Log.d(TAG, "seconds:" + seconds);
int minutes = seconds / 60;
Log.d(TAG, "minutes:" + minutes);
int hours = minutes / 60;
Log.d(TAG, "hours:" + hours);
int days = hours / 24;
Log.d(TAG, "days:" + days);
int weeks = days / 7;
Log.d(TAG, "weeks:" + weeks);
//months.. another way calculating data due not equal amount of days per month
Calendar temp = ((Calendar) then.clone());
temp.add(Calendar.MONTH, -now.get(Calendar.MONTH));
int months = temp.get(Calendar.MONTH);
Log.d(TAG, "months:" + months);
StringBuilder sb = new StringBuilder();
String format = "%d months, %d days, %d weeks";
String formatStr = String.format(format, months, days, weeks);
String result = sb.append(formatStr).toString();
Log.d(TAG, sb.toString());
return result;
}
private Calendar setDate(int day, int month, int year) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Log.d(TAG, c.getTime().toString());
return c;
}
Calendar c = calendar.getInstance();
and DatePickerDialog d
#Override
public void onDateSet(DatePicker view,int Year,int mont of Year,int day of month){
Toast
c.get(Calendar.Year),c.get(Calendar.Month),c.get(Calendar.Day_of_Month);
d.show
this code is to find week from selected date,it's proper work.
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(Integer.parseInt(selected_year), Integer.parseInt(selected_month), Integer.parseInt(selected_date)); // set date 1 (yyyy,mm,dd)
System.out.println("Selected Date==>>" + date1);
date2.clear();
date2.set(Integer.parseInt(current_year), Integer.parseInt(current_month), Integer.parseInt(current_date));
System.out.println("Current Date==>>" + date2);
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
week = (int) (dayCount / 7);
if (week <= 0) {
Toast.makeText(this, "Sry System Error", Toast.LENGTH_SHORT).show();
System.out.println("Week==>>" + week);
test = false;
} else {
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
System.out.println("Week==>>" + week);
test = true;
}
I want to find difference between 2 Date in months and days using Java. For example: difference between 5/16/2013 and 7/20/2013 is 2 months and 4 days.
Thank you for your consideration on this matter.
Use joda time library as its better to handle dates http://joda-time.sourceforge.net/
Something like this Days.daysBetween(first DateTime, second DateTime).getDays();
I would do it like this
Calendar c1 = new GregorianCalendar(2012, 0, 1);
Calendar c2 = new GregorianCalendar(2013, 0, 2);
int monthDiff = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
int dayDiff;
if (c1.get(Calendar.DATE) < c2.get(Calendar.DATE)) {
monthDiff--;
dayDiff = c1.getActualMaximum(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DATE) + c2.get(Calendar.DATE);
} else {
dayDiff = c2.get(Calendar.DATE) - c1.get(Calendar.DATE);
}
System.out.println(monthDiff + " " + dayDiff);
Try this one
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
int diff = getMonthDifference(date1, date2);
System.out.println(diff);
public static int getMonthDifference(java.util.Date date1, java.util.Date date2) {
if (date1.after(date2)) {
return getMonthDifference0(date1, date2);
} else if (date2.after(date1)) {
return -getMonthDifference0(date2, date1);
}
return 0;
}
private static int getMonthDifference0(java.util.Date date1, java.util.Date date2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
int diff = 0;
while (c2.getTimeInMillis() < c1.getTimeInMillis()) {
c2.add(Calendar.MONTH, 1);
diff++;
}
int dd = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);
if (dd > 0) {
diff--;
} else if (dd == 0) {
int hd = c2.get(Calendar.HOUR_OF_DAY) - c1.get(Calendar.HOUR_OF_DAY);
if (hd > 0) {
diff++;
} else if (hd == 0) {
long t1 = c1.getTimeInMillis() % (60 * 1000);
long t2 = c2.getTimeInMillis() % (60 * 1000);
if (t2 > t1) {
diff--;
}
}
}
return diff;
}
Nobody said console.log( new Date("2013-09-30") - new Date("2012-01-01") ); It will give you difference in milliseconds. Its up to you to handle time zones and so forth when creating those 2 objects.