Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get current date with start time and end time?

    • 0
    • 3
    • 2
    • 2
    • 0
    • 0
    • 0
    • 0
    • 574
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: