我正在尝试格式化具有以下格式的date
密钥的JSON:
日期:“2017-05-23T06:25:50”
我目前的尝试如下:
private String formatDate(String date) {
SimpleDateFormat format = new SimpleDateFormat("MM/DD/yyyy");
String formattedDate = "";
try {
formattedDate = format.format(format.parse(String.valueOf(date)));
} catch (ParseException e) {
e.printStackTrace();
}
return formattedDate;
}
但在这种情况下,结果没有显示在我的应用程序中,TextView
是隐形的,我无法记录任何东西。
我真的尝试过其他解决方案,但对我来说没有成功。我不知道是不是因为传入的值是一个字符串。
使用此代码格式化您的“2017-05-23T06:25:50”
String strDate = "2017-05-23T06:25:50";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(strDate);
SimpleDateFormat sdfnewformat = new SimpleDateFormat("MMM dd yyyy");
String finalDateString = sdfnewformat.format(convertedDate);
} catch (ParseException e) {
e.printStackTrace();
}
转换后的finalDateString
设置为你的textView
这对你有用。
String oldstring= "2017-05-23T06:25:50.0";
Date datee = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(oldstring);
使用此功能:
private String convertDate(String dt) {
//String date="2017-05-23T06:25:50";
try {
SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); //date format in which your current string is
Date newDate = null;
newDate = spf.parse(dt);
spf = new SimpleDateFormat("MM/DD/yyyy"); //date format in which you want to convert
dt = spf.format(newDate);
System.out.println(dt);
Log.e("FRM_DT", dt);
} catch (ParseException e) {
e.printStackTrace();
}
return dt;
}
这段代码对我有用:
public static String getNewsDetailsDateTime(String dateTime) {
@SuppressLint("SimpleDateFormat") DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = null;
try {
date = format.parse(dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
@SuppressLint("SimpleDateFormat") String strPublishDateTime = new SimpleDateFormat("MMM d, yyyy h:mm a").format(date);
return strPublishDateTime;
}
输出格式为:2017年12月20日下午2:30。
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/uuuu");
private static String formatDate(String date) {
return LocalDateTime.parse(date).format(DATE_FORMATTER);
}
现在formatDate("2017-05-23T06:25:50")
返回所需的05/23/2017
字符串。
在2017年,我认为没有理由为什么你应该与长期过时和臭名昭着的麻烦的SimpleDateFormat
课程斗争。 java.time
,现代Java日期和时间API,也称为JSR-310,使用起来非常好。
通常,当从一种日期时间格式转换为另一种格式时,您需要两种格式化程序,一种用于解析输入格式,另一种用于格式化为输出格式。不在这里。这是因为像2017-05-23T06:25:50
这样的字符串是ISO 8601格式,现代类解析为默认格式,即没有明确的格式化程序。所以我们只需要一个格式化器来进行格式化。
当我运行你的代码时,我得到了一个ParseException: Unparseable date: "2017-05-23T06:25:50"
。如果您没有注意到异常,那么您的项目设置中存在严重缺陷,会隐藏有关您的错误的重要信息。请先修复一下。
ParseException
有一个方法getErrorOffset
(有点被忽略),在这种情况下返回4.你的字符串中的偏移量4是第一个连字符的位置。因此,当以MM/DD/yyyy
格式解析时,你的SimpleDateFormat
接受2017年作为一个月(有趣,不是吗?),然后预期斜线并改为连字符,因此抛出异常。
您的格式模式字符串中有另一个错误:大写DD
表示每年的日期(本例中为143)。小写dd
应该用于日期。
java.time
吗?是的你可以。它至少需要Java 6。
java.time
。