Java Date - Android Time Picker - java

I'm having trouble getting the right format here. I'm trying to get a proper date from my android date picker to shove into a date object.
For example:
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
Those event handlers will give me: 2011, 7, 5 10,30 (if the date was August 5th, 2011 and the time was 10:30) Where do I get Am/Pm in Android?
I'm doing this but its not working right:
Date date = new Date(year,monthOfYear,dayOfMonth,hourOfDay,minute);
I need to accomplish the Android equivalent of this blackberry code. Blackberry date picker graciously provides a date object (rather than raw integers):
public void run() {
DateTimePicker datePicker = DateTimePicker.createInstance();
// Set the max time to 24 hours into the future. This allows for selecting clips
// across time zones, but prevents the user from wandering off into no-mans' land.
Calendar maxDateTime = Calendar.getInstance();
maxDateTime.setTime(new Date(System.currentTimeMillis() + 24*3600*1000));
datePicker.setMaximumDate(maxDateTime);
if (datePicker.doModal())
{
Calendar selectedDate = datePicker.getDateTime();
Date beforeDate = selectedDate.getTime();
ClipStore.getInstance().getClips(camera, beforeDate);
}
}

Use a Calendar :
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DATE, dayOfMonth);
cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
The hour of day goes from 0 to 23.

I believe that hourOfDay uses 24-hour time, so it should be a value between 0 and 23 inclusive. If it's greater >=12, it's PM.

By stock the Java.util will use Military time. aka 10:30 refers to 10:30 AM. 10:30 pm will be shown as 22:30. If you want to convert it to pm try something like this:
public String ampmChanger (String time) {
int hour = (int)time.substring(0,2);
String timeAppendage;
if (hour > 12) { // For 1 PM and on
hour -= 12;
timeAppendage = " PM";
}
else if (hour == 12) timeAppendage = " PM"; // For 12 pm
else timeAppendage = " AM"; // For 0(12AM) to Noon
return String.valueOf(hour)+time.substring(2)+timeAppendage;
}

Related

How to disable a button after a certain date [JAVA]

I was wondering how I could disable a button after a date like July 4, 2015?
I have found an example on this site of how to disable a button on that date but not the subsequent days after that date.
FROM Example:
Calendar today = Calendar.getInstance();
int dayOfMonth = today.get(Calendar.DAY_OF_MONTH);
int month = today.get(Calendar.MONTH);
int year = today.get(Calendar.YEAR);
if (month == Calendar.JUNE && dayOfMonth == 29 && year == 2014) {
// June 29, 2014
myButton.setEnabled(true);
}
else
{
// NOT June 29, 2014
myButton.setEnabled(false);
}
Here are a few ways that you can check your conditions :
Get an instance of the Calendar and set your prescribed date.
int dayOfMonth = 29;
int month = Calendar.JUNE;
int year = 2014;
Calendar disableDate = Calendar.getInstance();
disableDate.set(year, month, dayOfMonth);
Then: using the before/after/equals
//enable the button for dates after your prescribed date
if(today.after(disableDate))
//enable the button for dates before your prescribed date
if(today.before(disableDate))
//enable the button only on your prescribed date
if(today.equals(disableDate))
Note: You may have to strip off / zero time from the date instances if you are going to do any of these as the time will be taken into account.
To check for date equality:
public static boolean calendarCheck(Calendar calendar1, Calendar calendar2)
{
return zeroCalendar(calendar1).compareTo(zeroCalendar(calendar2)) == 0;
}
To zero Time
public static Calendar zeroCalendar(Calendar calendar)
{
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
I hope this helps.
Avoid java.util.Date and .Calendar classes bundled with Java. Instead use either Joda-Time or the new java.time package in Java 8 or later (inspired by Joda-Time).
Time Zone
Time zone is critical in determining the date. For example a new day dawns earlier in Paris than in Montréal where it is still 'yesterday'.
Joda-Time
LocalDate dueDate = new LocalDate( 2015 , DateTimeConstants.JULY , 4 ) ;
DateTimeZone zone = DateTimeZone.forID( "America/Montréal" ) ;
LocalDate now = LocalDate.now( zone ) ;
Boolean disableButton = now.isAfter( dueDate ) ;

Get next Date from day hour:minutes

I am trying to get the next Date that match a date format, like getting next Date that match "1 10:00" (format: u HH:mm).
Example: If we are Tuesday June 2 - 22:00 (for example), I want to get Sunday June 7 - 10:00 as a Date object (because it does match "1 10:00" format)
EDIT: It was "u" instead of "F", sorry !
If I understand good your question, this will do the trick. Basically adding 1 minute to current date until you find your desired date by its format.
You'd want to set a safest condition than true.
Calendar calendar = Calendar.getInstance();
Date date = new Date("06/02/2015 10:00");
calendar.setTime(date);
SimpleDateFormat sdf = new SimpleDateFormat("F HH:mm");
while (true) {
calendar.add(Calendar.MINUTE, 1);
if (sdf.format(calendar.getTime()).equals(sdf.format(date))) {
System.out.println(calendar.getTime());
break;
}
}
This prints:
Wed Jun 03 10:00:00 VET 2015 ... and 1440 minutes were added.
I finally found a solution myself :
public static Date getNextDate(SimpleDateFormat format, String value) {
try {
Date date = format.parse(value);
Calendar calendar = Calendar.getInstance();
int diff = date.getDay() - calendar.get(Calendar.DAY_OF_WEEK);
if (!(diff > 0)) {
diff += 7;
}
calendar.add(Calendar.DAY_OF_MONTH, diff);
calendar.set(Calendar.HOUR_OF_DAY, date.getHours());
calendar.set(Calendar.MINUTE, date.getMinutes());
calendar.set(Calendar.MINUTE, date.getSeconds());
return calendar.getTime();
} catch (ParseException exception) {
exception.printStackTrace();
}
return null;
}
It will return the next date that match my format. I use deprecated methods but I will fix it asap.
Thanks for helping anyway !

get startday of month and endday of month using calendar class in Java

Given a year and a month; I want to get two Date Objects. one for startDate of the month and one for the end Date of the month. I have it implemented here and it works. but this looks too verbose, and I am wondering if there is a neat solution to this;
Eg given March 2014,
start Date will be March 01 and end Date will be March 31 ( as Date objects with millisecond precision)
public setDates(int month,int year) {
Calendar calendar = Calendar.getInstance();
// Use the calendar to get the startDate and endDate of this Invoice.
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH,month);
//set start date
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY,
calendar.getActualMinimum(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE,
calendar.getActualMinimum(Calendar.MINUTE));
calendar.set(Calendar.SECOND,
calendar.getActualMinimum(Calendar.SECOND));
calendar.set(Calendar.MILLISECOND,
calendar.getActualMinimum(Calendar.MILLISECOND));
this.startDate = calendar.getTime();
//endDate start date
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY,
calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE,
calendar.getActualMaximum(Calendar.MINUTE));
calendar.set(Calendar.SECOND,
calendar.getActualMaximum(Calendar.SECOND));
calendar.set(Calendar.MILLISECOND,
calendar.getActualMaximum(Calendar.MILLISECOND));
this.endDate = calendar.getTime();
}
You can make this code considerably simpler by making some assumptions:
The first day of the month is always day 1
The minimum hour will always be 0
... etc
You can then find the last millisecond of the month by adding one month and subtracting a millisecond.
So the code could look like this:
// Note year/month reversal: try to consistently use larger units first. It
// makes for a cleaner API.
public setDates(int year, int month, TimeZone zone) {
Calendar calendar = Calendar.getInstance(zone);
// Do you really want 0-based months, like Java has? Consider month - 1.
calendar.set(year, month, 1, 0, 0, 0);
calendar.clear(Calendar.MILLISECOND);
startDate = calendar.getTime();
// Get to the last millisecond in the month
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.MILLISECOND, -1);
endDate = calendar.getTime();
}
To use an exclusive upper bound (as I'd recommend), just get rid of the calendar.add(Calendar.MILLISECOND, -1) near the end.
Oh, and I'd thoroughly recommend using Joda Time instead of java.util.Date etc - it's a much cleaner API.
Take March 1st. Add 1 to the month field. Then subtract 1 day.
Here is your last day of the month.
The first day is clear, it is 1st of month of year.
Verbose is OK, there's no much less verbose code version
(in JDK <= 7) if you stick to Java's built-in libraries.
use JODA, please.
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
public class Dates {
/**
* #param args
*/
public static void main(String[] args) {
//without JODA
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Helsinki"));
calendar.set(1921, 4, 1, 0, 0, 0);
calendar.clear(Calendar.MILLISECOND);
Date startDate = calendar.getTime();
System.out.println(startDate);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.MILLISECOND, -1);
Date endDate = calendar.getTime();
System.out.println(endDate);
/*
* Sat Apr 30 19:20:08 BRT 1921
* Tue May 31 19:20:07 BRT 1921
*/
//with JODA
DateTimeZone zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/Helsinki"));
DateTime dt = new DateTime(1921, 4, 1, 0, 0, 0, 0, zone);
DateTime plusPeriod = dt.plus(Period.months(1)).minus(Period.millis(1));
System.out.println(dt);
System.out.println(plusPeriod);
/*
* 1921-04-01T00:00:00.000+01:39:52
* 1921-04-30T23:59:59.999+01:39:52
*/
}
}

How to ignore time while checking date using before(Date d)

I know alternate methods to check next date but I would like to know is there any possibility of ignoring checking time when using before.
I have the following code
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
try {
if (fired == true) {
return;
} else {
// first time fired
fired = true;
}
String date = checkDigit(monthOfYear + 1) + "/"
+ checkDigit(dayOfMonth) + "/" + year;
strDate = date;
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date d=df.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
if(d.before(cal.getTime()))
{
etDOB.setText(strDate);
}
else
{
Toast.makeText(context, "Enter Valid Date Of Birth", Toast.LENGTH_SHORT).show();
etDOB.setText(" ");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
d.before(cal.getTime()) checking date but if the selected Date is next Date than it also checking time
Example :
Date value selected is feb 24 2013 so d contains the same
cal.getTime() also contains feb 24 2013
but the first date having the time 00:00:00 GMT+5:30 and second has the time 1:00:00 GMT+5:30 this cause the condition to fail. So my question is how do Ignore before to check time.
You can format and parse the date from cal.getTime() using df (SimpleDateFormat("MM/dd/yyyy")) which will get rid of time and then compare the result with d.
While createing the Calendar Object
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
cal.set(Calendar.Minute, 0);
cal.set(Calendar.Second, 0);
now your condition will not fail

Android: How to calculate a date some days ago?

I get the today's date like this:
final Calendar cal = Calendar.getInstance();
{
mYear = cal.get(Calendar.YEAR);
mMonth = cal.get(Calendar.MONTH);
mDay = cal.get(Calendar.DAY_OF_MONTH);
}
I want to calculate what was the date x days ago... anyone got something?
A better way would be to use add method instead of set:
cal.add(DAY_OF_YEAR, -2);
I.e. to be sure it works also the first day in month etc.
You can do the following :
Calendar cal=Calendar.getInstance();
int currentDay=cal.get(Calendar.DAY_OF_MONTH);
//Set the date to 2 days ago
cal.set(Calendar.DAY_OF_MONTH, currentDay-2);
then you can get the date :
cal.getTime(); //The date 2 days ago
I use the following fuction:
public static Date getStartOfDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
public static long getDaysAgo(Date date){
final long diff = getStartOfDay().getTime() - date.getTime();
if(diff < 0){
// if the input date millisecond > today's 12:00am millisecond it is today
// (this won't work if you input tomorrow)
return 0;
}else{
return TimeUnit.MILLISECONDS.toDays(diff)+1;
}
}
Same kind of code, but using the Joda-Time 2.3 library and Java 7.
DateTime dateTime = new DateTime( 2014, 2, 3, 7, 8, 9 );
DateTime twoDaysPrior = dateTime.minusDays( 2 );
dateTime: 2014-02-03T07:08:09.000-08:00
twoDaysPrior: 2014-02-01T07:08:09.000-08:00

Categories

Resources