當我嘗試使用此代碼時,為什么會出現錯誤:
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)
}
它說無法格式化給定物件的日期。我"2022-01-10T14:55:18.523"在變數中有一個值current。

編輯
我嘗試使用此代碼:
current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd")
val formatted = formatter.format(current)
return sharedPreferences.getString("currentDate", formatted)
但它給了我一個像這樣的錯誤:

uj5u.com熱心網友回復:
替換DateTimeFormatter而不是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);
}
}
uj5u.com熱心網友回復:
您遇到此錯誤是因為您使用 ajava.text.SimpleDateFormat來格式化java.time.LocalDateTime.
我認為這是不可能的,但即使是這樣,最好還是建議您不要混合使用這兩個 api。
您應該改用 a DateTimeFormatterand due to 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)
用這些
val formatter = DateTimeFormatter.ofPattern("uuuu/MM/dd")
val formatted = current.format(formatter)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/407459.html
標籤:
