I have date as a string like this
String date = "11-12-2018"
I want to change it to "2018-12-11"
with the same variable. So, I tried the code below but it doesn't give me the output I expect.
String date = "11-12-2018"
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d = df.parse(date);
results in: "0012-06-09"
I want "2018-12-11"
Try code below that will work for your case:
First parse your input format from string,
Then convert it to desired format,
Try the code below that will work
1) Make method like below
1st argument of the method is your current date format in your case it will be 'dd-MM-yyyy'
2nd argument is output or requires date format in your case it will be 'yyyy-MM-dd'
3rd argument is your date that you want to change the format
2) Run the method like below
3) Output:
You can do this 3 ways. First is using
SimpleDateFormat
andDate
and second usingDateTimeFormatter
andLocalDate
and third you can useSplit
.1. Using Date and SimpleDateFormat
Here we have our actual date
String date = "11-12-2018";
we know we want to change it to2018-12-11
So lets parse that date into a
Date
object using this codeOkay so now we have a date object of our actual date, Now lets format it to our new date.
2. Using LocalDate and DateTimeFormatter
Alright here we define our date again and 2 DateTimeFormatter.
The first formatter is our old date format, and the second one is the new one that we are gonna convert the old date into.
Alright lets use them now!
Now we make a new
LocalDate
object using our oldFormatter by parsing ourdateString
with theoldFormatter
objectAlright now lets format it.
as simple as that! Here is the full code.
3. Using String::Split
Okay this part is pretty simple. Lets split the date using
-
We already know the order of the date lets format it using
String::format
Here is the full code
This is the common function which I use for date and time conversion
You just have to pass the date string and their old and new formats. In your case call this function like this