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);
}
}
Output:
dd-MMMM-yyyy format:
31-March-2016
dd-MM-yyyy format:
31-03-2016
dd-MMMM-yyyy hh:mm:ss format:
31-March-2016 04:10:10
MM/dd/yyyy format:
03/31/2016
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)