Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to date then format the date

I am formatting a string to a date using the code

String start_dt = '2011-01-01';

DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); 
Date date = (Date)formatter.parse(start_dt);

But how do I convert the date from YYYY-MM-DD format to MM-DD-YYYY format?

like image 377
Mike Avatar asked Oct 24 '11 21:10

Mike


People also ask

Can we convert string to Date?

Let's see how to actually convert a String to a local date and time data type: Parse the API call: If the String value that we need to convert to the Date-time type is of ISO-801 format then we can simply call DateFormat and SimpleDateFormat classes using parse() methods.

Which function is used convert string into Date format?

Date() Function. as. Date() function in R Language is used to convert a string into date format.


2 Answers

Use SimpleDateFormat#format(Date):

String start_dt = "2011-01-01";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD"); 
Date date = (Date)formatter.parse(start_dt);
SimpleDateFormat newFormat = new SimpleDateFormat("MM-dd-yyyy");
String finalString = newFormat.format(date);
like image 53
MByD Avatar answered Sep 18 '22 22:09

MByD


String start_dt = "2011-01-31";

DateFormat parser = new SimpleDateFormat("yyyy-MM-dd"); 
Date date = (Date) parser.parse(start_dt);

DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); 
System.out.println(formatter.format(date));

Prints: 01-31-2011

like image 33
Bhesh Gurung Avatar answered Sep 18 '22 22:09

Bhesh Gurung