I want to change date format from "dd/mm/yyyy
" to "yyyy/mm/dd
" with one line in java8 stream
List<String[]> date = new ArrayList<>();
String[] a= {"12/2/2018","a1","a2"};
String[] b= {"13/3/2018","b1","b2"};
String[] c= {"14/4/2018","c1","c2"};
date.add(a)`
date.add(b);
date.add(c);
I expect the output is
{{"2018/2/12","a1","a2"},{"2018/2/13","b1","b2"},{"2018/2/14","c1","c2"}}
Using java. The LocalDate class represents a date-only value without time-of-day and without time zone. String input = "January 08, 2017"; Locale l = Locale.US ; DateTimeFormatter f = DateTimeFormatter. ofPattern( "MMMM dd, uuuu" , l ); LocalDate ld = LocalDate. parse( input , f );
String mydateStr = "/107/2013 12:00:00 AM"; DateFormat df = new SimpleDateFormat("/dMM/yyyy HH:mm:ss aa"); Date mydate = df. parse(mydateStr); Two method above can be used to change a formatted date string from one into the other. See the javadoc for SimpleDateFormat for more info about formatting codes.
First you have to parse the string representation of your date-time into a Date object. DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = (Date)formatter. parse("2011-11-29 12:34:25");
I hope you mean yyyy/MM/dd
coz m is for minutes and M for month...
consider a Map from the stream API
public static void main(String[] args) {
List<String[]> date = new ArrayList<>();
String[] a= {"12/2/2018","a1","a2"};
String[] b= {"13/3/2018","b1","b2"};
String[] c= {"14/4/2018","c1","c2"};
date.add(a);
date.add(b);
date.add(c);
List<String[]> even = date.stream().map(
s -> {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
LocalDate localDate = LocalDate.parse(s[0], formatter);
DateTimeFormatter formatterNew = DateTimeFormatter.ofPattern("yyyy/MM/dd");
return new String[]{formatterNew.format(localDate), s[1],s[2]};
}
).collect(Collectors.toList());
even.forEach(x-> System.out.println(Arrays.toString(x)));
}
that will print out
[2018/02/12, a1, a2]
[2018/03/13, b1, b2]
[2018/04/14, c1, c2]
You can not do this without iterating over all items.
For your simple case dd/mm/yyyy
to yyyy/mm/dd
you can just use this:
date.forEach(i -> {
String[] parts = i[0].split("/");
i[0] = parts[2] + "/" + parts[1] + "/" + parts[0];
});
Using java time api you can use this:
DateTimeFormatter toFormat = DateTimeFormatter.ofPattern("yyyy/M/d");
DateTimeFormatter fromFormat = DateTimeFormatter.ofPattern("d/M/yyyy");
date.forEach(i -> i[0] = LocalDate.parse(i[0], fromFormat).format(toFormat));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With