Sometimes we need to get current date but we need to get time with date that starts from 12 O'clock morning and sometimes ends with 12 O'clock night.
To achieve this use the below code:
1- Write the below code to set time fields to start
/**
* Set time fields to start
* @param calendar
*/
public static void setTimeFieldsToStart(Calendar calendar)
{
// Set time fields to end
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
2- Write the below code to set time fields to end
/**
* Set time fields to end
* @param calendar
*/
public static void setTimeFields(Calendar calendar)
{
// Set time fields to end
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 59);
}
3- Now write the below functiona to get cuurent date with time fields set to start:
/**
* Get current date
* @return
*/
public static Date getCurrentDate()
{
try {
Calendar c = Calendar.getInstance();
// Set time fields to end
setTimeFieldsToStart(c);
return c.getTime();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
4- Now write the below functiona to get cuurent date with time fields set to end:
/**
* Get current date for event
* @return
*/
public static Date getCurrentDateForEvent()
{
try {
Calendar c = Calendar.getInstance();
// Set time fields to end
setTimeFieldsToStart(c);
return c.getTime();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Hope this will help you :)
0 Comment(s)