I hit API that will return date in datetime type. The example of the return is "1994-12-03T12:00:00" and I want to modify the return become "Pca19941203". The return will be apply in csv file. I do the modification in Java. Is there some ways to do that ?
Asked
Active
Viewed 90 times
-2
-
Convert the `String` value to a `LocalDateTime` object and format as you need – MadProgrammer Jan 17 '20 at 01:19
2 Answers
1
Java 8+ (Recommended):
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime.parse("1994-12-03T12:00:00")
.format(DateTimeFormatter.ofPattern("'Pca'uuuuMMdd"))
Joda-Time:
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
LocalDateTime.parse("1994-12-03T12:00:00")
.toString(DateTimeFormat.forPattern("'Pca'yyyyMMdd"))
Old Java API:
import java.text.SimpleDateFormat;
new SimpleDateFormat("'Pca'yyyyMMdd").format(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.parse("1994-12-03T12:00:00"))
Output (from all 3)
Pca19941203

Andreas
- 154,647
- 11
- 152
- 247
-
1Thank you for your answer. It works for me. I use the Java 8+ solution. – christine vincenza Jan 17 '20 at 08:51
0
You can to do the next
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class as {
public static void main(String[] args) {
Long tmp = castDateToString(new Date());
System.out.println(tmp);
//Devolver al servicio
System.out.println(returnServiceFormat(tmp, "yyyy/MM/dd"));
}
public static long castDateToString(Date system) {
return system.getTime();
}
public static String returnServiceFormat(long date, String format) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
DateFormat df = new SimpleDateFormat(format);
return String.valueOf(df.format(calendar.getTime()));
}
}
The result was
run: 1579226334699 2020/01/16 BUILD SUCCESSFUL (total time: 0 seconds)

Alejandro Gonzalez
- 1,221
- 4
- 15
- 30
-
1Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jan 17 '20 at 02:58
-
-
See the *Java8+* section if the answer by Andreas. That's how I recommend doing. Also see [the top voted answer to the link original question](https://stackoverflow.com/a/4772461/5772882) and the *Java 8 update* section of [the accpeted answer to the other linked question](https://stackoverflow.com/a/4216767/5772882). – Ole V.V. Jan 20 '20 at 18:54