Why do I get an error when I try using this code:
get() {
current = LocalDateTime.now()
val sharedPreferences = ctx.getSharedPreferences(COMMON_MANAGER, Context.MODE_PRIVATE)
val formatter = SimpleDateFormat("yyyy/MM/dd")
val formatted = formatter.format(current)
return sharedPreferences.getString("currentDate", formatted)
}
It says cannot format given object a date. I have a value of "2022-01-10T14:55:18.523" in the variable current.
EDIT
I tried using this code :
current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd")
val formatted = formatter.format(current)
return sharedPreferences.getString("currentDate", formatted)
But it gives me an error like so:
CodePudding user response:
Replace DateTimeFormatter instead of SimpleDateFormat
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Scratch {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String result = formatter.format(now);
System.out.println(result);
}
}
CodePudding user response:
You are experiencing this error because you are using a java.text.SimpleDateFormat to format a java.time.LocalDateTime.
I don't think that's possible, but even if it is you will be best adviced not to mix those two apis.
You should instead use a DateTimeFormatter and due the pattern you have used in your SimpleDateFormat("yyyy/MM/dd") I would replace the lines
val formatter = SimpleDateFormat("yyyy/MM/dd")
val formatted = formatter.format(current)
with these
val formatter = DateTimeFormatter.ofPattern("uuuu/MM/dd")
val formatted = current.format(formatter)


