DATE TO STRING CONVERSION IN JAVA
package basic;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToString {
public static void main(String[] args) {
// STEP1- create a Date object
Date date = new Date();
System.out.println("Date is: " + date);
// STEP2- creates object of SimpleDateFormat(java.text.SimpleDateFormat)
// and pass the date format into its constructor
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
// STEP 3- use the format() method of SimpleDateFormat and put object of
// Date(creates in STEP 1) into constructor and format() method will
// return String date with pass format date( in Step 2)
String stringDate = simpleDateFormat.format(date);
System.out.println("after convert: " + stringDate);
// see here you can take any date format in parameter,and keep in mind
// here month is in capital MM.if you take lowercase mm then it wont
// give compilation error but give any values but not exact month,,same
// as with date and year
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
String date2 = format1.format(date);
System.out.println("in different format: " + date2);
}
}
output-->
Date is: Thu Jun 02 18:18:55 IST 2016
after convert: 02/06/2016
in different format: 06/02/2016
package basic;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToString {
public static void main(String[] args) {
// STEP1- create a Date object
Date date = new Date();
System.out.println("Date is: " + date);
// STEP2- creates object of SimpleDateFormat(java.text.SimpleDateFormat)
// and pass the date format into its constructor
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
// STEP 3- use the format() method of SimpleDateFormat and put object of
// Date(creates in STEP 1) into constructor and format() method will
// return String date with pass format date( in Step 2)
String stringDate = simpleDateFormat.format(date);
System.out.println("after convert: " + stringDate);
// see here you can take any date format in parameter,and keep in mind
// here month is in capital MM.if you take lowercase mm then it wont
// give compilation error but give any values but not exact month,,same
// as with date and year
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
String date2 = format1.format(date);
System.out.println("in different format: " + date2);
}
}
output-->
Date is: Thu Jun 02 18:18:55 IST 2016
after convert: 02/06/2016
in different format: 06/02/2016
No comments:
Post a Comment