You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SimpleDateFormat日值异常:Android应用中解析日期得到38的问题

解决SimpleDateFormat解析日期日值异常的问题

嘿,这个问题我之前也踩过坑!你遇到的日值变成38的问题,根源出在日期格式字符串的格式符误用上。

  • 你当前用的"yyyy/MM/DD"里,大写的DD代表的是一年中的第几天(Day of Year),所以38其实是当前日期在这一年里的顺位天数,并不是当月的具体日期。
  • 要是想获取当月的第几天,得用小写的dd,正确的格式字符串应该是"yyyy/MM/dd"。

修正后的代码示例:

Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = sdf.format(currentTime);

另外给你个小建议:如果你的项目支持Android 8.0(API 26)及以上版本,更推荐用Java 8引入的java.time系列API(比如LocalDate、DateTimeFormatter),它们比SimpleDateFormat更线程安全、可读性也更强,示例代码如下:

LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String formattedDate = currentDate.format(formatter);

内容的提问来源于stack exchange,提问作者ismail alaoui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:14:13