Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Sunday 19 August 2018

Java : Convert Date to String example

                              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  :

  1. DateFormat is used for formatting a date into String based on specific locale that is provided as input.
  2. The locale is used for specifying the region and language for making the code more locale to the user.
  3. 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.
  4. 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