Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Formatting date in different format in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 550
    Comment on it

    Formatting Date in java:

    There is a predefined format for dealing with dates in java , but suppose if you want the date in some other format other than the default one then you can use the SimpleDateFormat class of the java.text package.

    e.g Suppose you only want the date without the time and year, then you can make use of this to format the date.

    Lets see an example for some different date formats in java:

    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class DateFormat {
    	public static void main(String args[])
    	   Date date = new Date();  
    	    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMMM-yyyy");  
    	    String formattedDate = dateFormat.format(date);  
    	    System.out.println("dd-MMMM-yyyy format:\n"+formattedDate);  
    	    dateFormat = new SimpleDateFormat("dd-MM-yyyy");  
    	    formattedDate = dateFormat.format(date);  
    	    System.out.println("dd-MM-yyyy format:\n"+formattedDate);  
    	    dateFormat = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss");  
    	    formattedDate = dateFormat.format(date);  
    	    System.out.println("dd-MMMM-yyyy hh:mm:ss format:\n"+formattedDate);  
    	    dateFormat = new SimpleDateFormat("MM/dd/yyyy");  
    	    formattedDate = dateFormat.format(date);  
    	    System.out.println("MM/dd/yyyy format:\n"+formattedDate);  
    	    dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");  
    	    formattedDate = dateFormat.format(date);  
    	    System.out.println("E, dd MMM yyyy HH:mm:ss z format:\n"+formattedDate);  


    dd-MMMM-yyyy format:
    dd-MM-yyyy format:
    dd-MMMM-yyyy hh:mm:ss format:
    31-March-2016 04:10:10
    MM/dd/yyyy format:
    E, dd MMM yyyy HH:mm:ss z format:
    Thu, 31 Mar 2016 16:10:10 IST

    In this, format() method present in SimpleDateFormat takes the target date format as the input and return the date in desired format in the form of String.

    This way you can format the date in the desired format and use it as per your requirement.

 0 Comment(s)

Sign In

Sign up using

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: