Example
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class DateToStringConvert {
public static void main(String args[]){
Date date = new Date();
/*To convert java.util.Date to String, use SimpleDateFormat class.*/
DateFormat dateFormat = new SimpleDateFormat(“yyyy-mm-dd hh:mm:ss”);
/*to convert Date to String, use format method of SimpleDateFormat class.*/
String strDate = dateFormat.format(date);
System.out.println(“Date converted to String: ” + strDate);
}
}
}
Here I use DateFormat Class :
- DateFormat is used for formatting a date into String based on specific locale that is provided as input.
- The locale is used for specifying the region and language for making the code more locale to the user.
- The way of writing date is different in different regions of the world. For example, 31st Dec 2017 will be written in India as 31-12-2017 but the same thing will be written in US as 12-31-2017.
- Date Format classes are not synchronized, it’s recommended to create separate instance for each thread.
SimpleDateFormat Class :
SimpleDateFormat is very much like DateFormat, the only major difference between them is that SimpleDateFormat can be used for formatting (Date to String conversion) and for parsing (String to Date conversion) both, whereas DateFormat allows only formatting of Date.
No comments:
Post a Comment