Get date and time from two Nebula CDateTime Widgets - java

How would you read date and time from two Nebula CDateTime widgets?
Here's my own answer, but I am sure there is a more efficient solution:
final Calendar calResult = Calendar.getInstance();
final Calendar calDate = Calendar.getInstance();
final Calendar calTime = Calendar.getInstance();
calResult.clear();
calDate.clear();
calTime.clear();
// read date
calDate.setTime(cdtDate.getSelection());
final int year = calDate.get(Calendar.YEAR);
final int month = calDate.get(Calendar.MONTH);
final int day = calDate.get(Calendar.DAY_OF_MONTH);
// read time
calTime.setTime(cdtTime.getSelection());
final int hour = calTime.get(Calendar.HOUR_OF_DAY);
final int minute = calTime.get(Calendar.MINUTE);
final int second = calTime.get(Calendar.SECOND);
// set date
calResult.set(Calendar.YEAR, year);
calResult.set(Calendar.MONTH, month);
calResult.set(Calendar.DAY_OF_MONTH, day);
// set time
calResult.set(Calendar.HOUR_OF_DAY, hour);
calResult.set(Calendar.MINUTE, minute);
calResult.set(Calendar.SECOND, second);
// return Date object
Date result = calResult.getTime();

Related

How to let the user pick the future date with datepickerdialog?

I want to let the user pick the date after today, as a remind date, how can I do it?Also, how can I put the theme inside these codes,because there is no button for the user to choose.
Here is my code combine with datapickerdialog and timepickerdialog:
private void setDateTimeField (){
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
day = selectedDate;
timePicker();
date_time = year + "-" + (month + 1) + "-" + day;
}
},year, month, day);
final Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy);
datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
datePickerDialog.show();
}
private void timePicker(){
// Get Current Time
final Calendar c = Calendar.getInstance();
hours = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,new
TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int
minute) {
hours = hourOfDay;
minutes = minute;
modifytime.setText(date_time+" "+hourOfDay + ":" +
minute);
}
}, hours, minutes, false);
timePickerDialog.show();
}
If you like to set the current date as minimum date and no past days should be selectable, then below solution will works I believe
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
//Min date setting part
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy);
//Replace your code mDatePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); with the below line
mDatePickerDialog.setMinDate(cal.getTimeInMillis());
Since you are allowing the user to select only future dates, you should not need to set Max date.
Complete Code sample for your reference -
private void showDateDailog() {
final DatePickerDialog datePickerDialog = new DatePickerDialog(getApplicationContext(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
day = selectedDate;
addtime.setText(new StringBuilder().append(year).append("/")
.append(month + 1).append("/").append(day));
}
}, year, month, day);
final Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
//Min date setting part
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy);
datePickerDialog.setMinDate(cal.getTimeInMillis());
//Maximum date setting part, if you need (Else don't add it)
/*Calendar calen = Calendar.getInstance();
calen.set(Calendar.MONTH, mm);
calen.set(Calendar.DAY_OF_MONTH, dd);
calen.set(Calendar.YEAR, yy + 2);
datePickerDialog.setMaxDate(calen.getTimeInMillis());*/
datePickerDialog.show();
}

Displaying local format in a custom dateTime picker in android

I am beginner coder, currently making a reminder app. So far this app does the following:
When you click the datetime picker it opens my custom datetime picker
You select the date and the time (that is at least 10 minutes from now and is in the next 30 days)
Date and time you selected displays in TextView field on screen
Since there is no datetime picker I made a custom one. I tried a number of approaches and this is the only one that worked for me. So now I have this problem - I want to display the date and the time format that is the same as the format on the phone - for USA it would be month/day/year and AM/PM, for Europe day/month/year and 24hr format. If there is no way to do this I would like to at least display the month name - like this 03 Mar. I used StringBuilder to append day, month and year. This can be confusing if the date is for example 02/03/2016. As for the time I am displaying 24 hour format with added "0" for one digit numbers.
As I said I am a beginner so I am having problems using examples like this with StringBuilder. I also tried this example instead of StringBuilder, but I got but I got incompatyble types error: required android.widget.TextView, found java.lang.String.
My current way of displaying the date and time is shown bellow in the "// Update date and time" section. The rest of the code is here for for reference for anyone who needs to create a custom datetime picker :)
private Button mPickDate;
private TextView mDateDisplay;
private TextView mTimeDisplay;
final Calendar c = Calendar.getInstance();
private int mYear = c.get(Calendar.YEAR);
private int mMonth = c.get(Calendar.MONTH);
private int mDay = c.get(Calendar.DAY_OF_MONTH);
private int mHour = c.get(Calendar.HOUR_OF_DAY);
private int mMinute = c.get(Calendar.MINUTE);
static final int TIME_DIALOG_ID = 1;
static final int DATE_DIALOG_ID = 0;
And the rest of the code:
//Update date and time
private void updateDate() {
mDateDisplay.setText(
new StringBuilder()
.append(mDay).append("/")
.append(mMonth + 1).append("/")
.append(mYear).append(" "));
showDialog(TIME_DIALOG_ID);
}
public void updateTime() {
mTimeDisplay.setText(
new StringBuilder()
.append(pad(mHour)).append(":")
.append(pad(mMinute)));
}
// Append 0 if number < 10
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
// Generate DatePickerDialog and TimePickerDialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
Calendar c2 = Calendar.getInstance();
if (mYear == c2.get(Calendar.YEAR)
&& mMonth == c2.get(Calendar.MONTH)
&& mDay == c2.get(Calendar.DAY_OF_MONTH)
&& (mHour < c2.get(Calendar.HOUR_OF_DAY) || (mHour == c2.get(Calendar.HOUR_OF_DAY) && mMinute <= (c2.get(Calendar.MINUTE) + 10))
)
) {
Toast.makeText(SetDateTimeActivity.this, "Set time at least 10 minutes from now", Toast.LENGTH_LONG).show();
} else {
updateTime();
}
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
c.add(Calendar.MONTH, +1);
long oneMonthAhead = c.getTimeInMillis();
datePickerDialog.getDatePicker().setMaxDate(oneMonthAhead);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
return datePickerDialog;
case TIME_DIALOG_ID:
TimePickerDialog timePickerDialog =
new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
return timePickerDialog;
}
return null;
}
Thank you in advance :)
EDIT - the solution I used in my code:
// Update date and time
private void updateDate() {
c.set(mYear, mMonth, mDay);
String date = new SimpleDateFormat("MMM dd, yyyy").format(c.getTime());
mDateDisplay.setText(date);
showDialog(TIME_DIALOG_ID);
}
public void updateTime() {
c.set(mYear, mMonth, mDay, mHour, mMinute); // check why do I need to add year,month,day
String time = new SimpleDateFormat(" hh:mm a").format(c.getTime());
mTimeDisplay.setText(time);
}
You can change the format whatever you want example is in below.
String strCurrentDate = "Wed, 18 Apr 2012 07:55:29 +0000";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z");
Date newDate = format.parse(strCurrentDate);
format = new SimpleDateFormat("MMM dd,yyyy hh:mm a");
String date = format.format(newDate);
Or your local format
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
String formatted = sdf .format(900000);
System.out.println(simpleDateFormat.parse(formatted));
or you can take year month day from calander and format it.
Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR);
cal.get(Calendar.DAY_OF_MONTH);
cal.get(Calendar.MONTH);
String format = new SimpleDateFormat("E, MMM d, yyyy").format(cal.getTime());
you just change the format for whatever your format search usa date format an put it in
SimpleDateFormat("here").format(cal.getTime());

Java - Know the day of the week of the given String

In android,I have a String of that format "2015-03-30T12:30:00" and I want to know which day of the week it is.
Testing with the device on the same day, with that function dayOfweek = 5 and dayOfWeek2 = 2 why?
if I try to create a new Date with year , month , day Its say is deprecated...
public int devolverDia(String hora)
{
hora = hora.substring(0, 10);
String weekdays[] = new DateFormatSymbols(Locale.ENGLISH).getWeekdays();
Calendar c = Calendar.getInstance();
int year = Integer.parseInt(hora.substring(0, 4));
int month = Integer.parseInt(hora.substring(5, 7));
int day = Integer.parseInt(hora.substring(8, 10));
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
c.setTime(new Date());
int dayOfWeek2 = c.get(Calendar.DAY_OF_WEEK);
return dayOfWeek;
}
The reason that you don't get the date that you expect is that the line
c.set(Calendar.MONTH, month);
expects a month number from 0 (for January) to 11 (for December). If you replace it with
c.set(Calendar.MONTH, month - 1);
this code will work.
However, a much better solution would be to use the parse method of the SimpleDateFormat class to convert your String to a Date.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
c.setTime(format.parse(hora));

How can I check if it is between 2pm and 1am new york time?

I need to check if the time in new york time zone is between 2pm and 1 am but i am not sure how to select the timezone or what to do next
String string1 = "14:00:00";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "01:00:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
If you're interested in whether the current time is "after or equal to 2pm, or before 1am" then don't need to use string parsing at all. You could use:
TimeZone zone = TimeZone.getTimeZone("America/New_York");
Calendar calendar = new GregorianCalendar(zone);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 1 || hour >= 14) {
...
}
That's assuming you do want it to match 3pm, but you don't want it to match 8am, for example. That's "between 2pm and 1am" in my view, as per your title.
If you're using Java 8, I'd suggest using LocalTime instead, via ZonedDateTime:
private static final LocalTime EARLY_CUTOFF = LocalTime.of(1, 0);
private static final LocalTime LATE_CUTOFF = LocalTime.of(14, 0);
ZoneId zone = ZoneId.of("America/New_York");
LocalTime time = ZonedDateTime.now(zone).toLocalTime();
if (time.compareTo(EARLY_CUTOFF) < 0 && time.compareTo(LATE_CUTOFF) >= 0) {
...
}
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
int curr_hour = calNewYork.get(Calendar.HOUR_OF_DAY);
System.out.println(curr_hour < 1 || curr_hour >= 14);

Start and end date of a current month

I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that?
For example if I select month May in a list box I need starting date that is 1 and end date that is 31.
There you go:
public Pair<Date, Date> getDateRange() {
Date begining, end;
{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
setTimeToBeginningOfDay(calendar);
begining = calendar.getTime();
}
{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
}
return Pair.of(begining, end);
}
private static Calendar getCalendarForNow() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
return calendar;
}
private static void setTimeToBeginningOfDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
private static void setTimeToEndofDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}
PS: Pair class is simply a pair of two values.
If you have the option, you'd better avoid the horrid Java Date API, and use instead Jodatime (or equivalently the Java 8 java.time.* API). Here is an example:
LocalDate monthBegin = new LocalDate().withDayOfMonth(1);
LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1);
Try LocalDate from Java 8:
LocalDate today = LocalDate.now();
System.out.println("First day: " + today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()));
Simple and Best, Try this One
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date monthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date monthLastDay = calendar.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String startDateStr = df.format(monthFirstDay);
String endDateStr = df.format(monthLastDay);
Log.e("DateFirstLast",startDateStr+" "+endDateStr);
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = 1;
c.set(year, month, day);
int numOfDaysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("First Day of month: " + c.getTime());
c.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + c.getTime());
With the date4j library :
dt.getStartOfMonth();
dt.getEndOfMonth();
Try this Code
Calendar calendar = Calendar.getInstance();
int yearpart = 2010;
int monthPart = 11;
int dateDay = 1;
calendar.set(yearpart, monthPart, dateDay);
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Number of Days: " + numOfDaysInMonth);
System.out.println("First Day of month: " + calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + calendar.getTime());
Hope it helps.
if you have java.time.YearMonth you can do:
YearMonth startYearMonth = YearMonth.now();
java.time.LocalDate startOfMonthDate = startYearMonth.atDay(1);
java.time.LocalDate endOfMonthDate = startYearMonth.atEndOfMonth();
Date begining, ending;
Calendar calendar_start =BusinessUnitUtility.getCalendarForNow();
calendar_start.set(Calendar.DAY_OF_MONTH,calendar_start.getActualMinimum(Calendar.DAY_OF_MONTH));
begining = calendar_start.getTime();
String start= DateDifference.dateToString(begining,"dd-MMM-yyyy");//sdf.format(begining);
// for End Date of month
Calendar calendar_end = BusinessUnitUtility.getCalendarForNow();
calendar_end.set(Calendar.DAY_OF_MONTH,calendar_end.getActualMaximum(Calendar.DAY_OF_MONTH));
ending = calendar_end.getTime();
String end=DateDifference.dateToString(ending,"dd-MMM-yyyy");//or sdf.format(end);
enter code here
public static Calendar getCalendarForNow() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
return calendar;
}
For Java 8+, below method will given current month first & last dates as LocalDate instances.
public static LocalDate getCurrentMonthFirstDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}
public static LocalDate getCurrentMonthLastDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}
Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
System.out.println("First day: " +
today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()))
}
You can implement it as below:
public void FirstAndLastDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
//start date of month
calendarStart = Calendar.getInstance();
calendarStart.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
, Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
, Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
//End Date of month
calendarEnd = Calendar.getInstance();
calendarEnd.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
, Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
, Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
Toast.makeText(this, sdf.format(calendarStart.getTime()) + "\n" + sdf.format(calendarEnd.getTime()), Toast.LENGTH_SHORT).show();
}
A very simple step to get the first day and last day of the month:
Calendar calendar = Calendar.getInstance();
// Get the current date
Date today = calendar.getTime();
// Setting the first day of month
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfMonth = calendar.getTime();
// Move to next month
calendar.add(Calendar.MONTH, 1);
// setting the 1st day of the month
calendar.set(Calendar.DAY_OF_MONTH, 1);
// Move a day back from the date
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
// Formatting the date
DateFormat sdf = new SimpleDateFormat("dd-MMM-YY");
String todayStr = sdf.format(today);
String firstDayOfMonthStr = sdf.format(firstDayOfMonth);
String lastDayOfMonthStr = sdf.format(lastDayOfMonth);
System.out.println("Today : " + todayStr);
System.out.println("Fist Day of Month: "+firstDayOfMonthStr);
System.out.println("Last Day of Month: "+lastDayOfMonthStr);
Making it more modular, you can have one main function that calculates startDate or EndDate and than you can have individual methods to getMonthStartDate, getMonthEndDate and to getMonthStartEndDate. Use methods as per your requirement.
public static String getMonthStartEndDate(){
String start = getMonthDate("START");
String end = getMonthDate("END");
String result = start + " to " + end;
return result;
}
public static String getMonthStartDate(){
String start = getMonthDate("START");
return start;
}
public static String getMonthEndDate(){
String end = getMonthDate("END");
return end;
}
/**
* #param filter
* START for start date of month e.g. Nov 01, 2013
* END for end date of month e.g. Nov 30, 2013
* #return
*/
public static String getMonthDate(String filter){
String MMM_DD_COMMA_YYYY = "MMM dd, yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(MMM_DD_COMMA_YYYY);
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
sdf.format(GregorianCalendar.getInstance().getTime());
Calendar cal = GregorianCalendar.getInstance();
int date = cal.getActualMinimum(Calendar.DATE);
if("END".equalsIgnoreCase(filter)){
date = cal.getActualMaximum(Calendar.DATE);
}
cal.set(Calendar.DATE, date);
String result = sdf.format(cal.getTime());
System.out.println(" " + result );
return result;
}

Categories

Resources