java create date object using a value string
Use SimpleDateFormat parse method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
String inputString = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(inputString, dateFormat );
Since we have Java 8 with LocalDate I would suggest use next:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
String inputString = "11-11-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate inputDate = LocalDate.parse(inputString,formatter);
import java.util.Date;
import java.text.SimpleDateFormat;
Above is the import method, below is the simple code for Date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
system.out.println((dateFormat.format(date)));
Whenever you want to convert a String to Date object then use SimpleDateFormat#parse
Try to use
String dateInString = new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime())
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss");
Date parsedDate = formatter.parse(dateInString);
.Additional thing is if you want to convert a Date
to String
then you should use SimpleDateFormat#format
function.
Now the Point for you is
new Date(String)
is deprecated and not recommended now.Now whenever anyone wants to parse , then he/she should use SimpleDateFormat#parse
.
refer the official doc for more Date and Time Patterns used in SimpleDateFormat options.