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

Java中Jalali历转Georgian历:转换结果指定格式输出问询

解决Jalali转Gregorian后的日期格式化问题

没问题!你现在的问题是调用dt.toString()会输出Date类的默认格式,不是你想要的2018/04/03这种yyyy/MM/dd样式对吧?我给你两种实用的解决方案,根据你的项目环境选择就行:

方法一:使用SimpleDateFormat(兼容旧版Android)

这是Android早期版本常用的方式,直接用SimpleDateFormat指定目标格式,把Date对象转换成字符串:

Date dt = JalaliCalendar.getGregorianDate("1397/01/14");
// 创建格式化实例,指定格式为yyyy/MM/dd
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
// 把Date对象格式化成目标字符串
String formattedDate = dateFormatter.format(dt);
// 显示格式化后的结果
Toast.makeText(getApplicationContext(), formattedDate, Toast.LENGTH_LONG).show();

注意:SimpleDateFormat不是线程安全的,如果是在多线程环境(比如后台线程)使用,最好每次创建新实例或者用线程安全的包装类。

方法二:使用DateTimeFormatter(推荐,Java 8+/Android API 26+或ThreeTenABP)

如果你用的是Android API 26及以上,或者引入了ThreeTenABP库(兼容低版本Android的Java时间API),推荐用Java 8新增的时间类,更安全且功能更强大:

Date dt = JalaliCalendar.getGregorianDate("1397/01/14");
// 把旧的Date对象转换成LocalDate(Java 8+日期类)
Instant instant = dt.toInstant();
LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
// 创建格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
// 格式化日期
String formattedDate = localDate.format(formatter);
// 显示结果
Toast.makeText(getApplicationContext(), formattedDate, Toast.LENGTH_LONG).show();

这种方式的优势是DateTimeFormatter是线程安全的,而且LocalDate等类设计更合理,避免了旧Date类的一些坑。

内容的提问来源于stack exchange,提问作者ebrahim babavand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:20:27