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

时间戳转波斯历时24小时制时间显示异常问题求助

解决波斯历转换中24小时制时间显示错误的问题

我来帮你分析下当前代码的问题,然后给出针对性的解决方案:

问题根源

你的代码里使用SimpleDateFormat时没有指定时区,它默认会用JVM的系统时区来格式化时间。如果你的时间戳是基于UTC的,而系统时区和伊朗时区(Asia/Tehran)不一致,就会出现时间偏移——比如把伊朗当地的中午12:45,显示成了系统时区的午夜00:45。另外提一句:24:13在标准24小时制里是不存在的,正确的写法就是次日的00:13,这部分是符合规则的,你不用调整这部分。


方案1:修复现有代码(快速生效)

只需要给SimpleDateFormat明确指定伊朗时区,就能保证时间转换的准确性:

private String getDate(long timestamp) {
    Date date = new Date(timestamp * 1000L);
    // **关键**:添加时区设置,确保用伊朗当地时间格式化
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH:mm", Locale.UK);
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
    
    String[] paths = sdf.format(date).split("/");
    CalendarTool ct = new CalendarTool(Integer.parseInt(paths[0]), Integer.parseInt(paths[1]), Integer.parseInt(paths[2]));
    return ct.getIranianDate().trim() + " - " + paths[3].trim();
}

测试你给出的示例时间戳1515186060:它对应的UTC时间是2018-01-06 12:41:00,指定伊朗时区后会转换为当地时间16:11:00,时间部分会正确显示为16:11,符合24小时制规则。


方案2:使用Java 8+新日期API(推荐)

SimpleDateFormat和Date是线程不安全的,Java 8引入的java.time包更可靠、API也更清晰。你可以借助Threeten-Extra库直接处理波斯历,不用依赖第三方的CalendarTool:

第一步:添加依赖(Maven为例)

<dependency>
    <groupId>org.threeten</groupId>
    <artifactId>threeten-extra</artifactId>
    <version>1.7.0</version>
</dependency>

第二步:改写代码

import org.threeten.extra.chrono.PersianChronology;
import org.threeten.extra.chrono.PersianDate;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

private String getDate(long timestamp) {
    // 把时间戳转换为伊朗时区的时间
    Instant instant = Instant.ofEpochSecond(timestamp);
    ZoneId tehranZone = ZoneId.of("Asia/Tehran");
    
    // 格式化24小时制时间
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm").withZone(tehranZone);
    String time = timeFormatter.format(instant);
    
    // 直接转换为波斯历日期
    PersianDate persianDate = PersianChronology.INSTANCE.date(instant.atZone(tehranZone).toLocalDate());
    String persianDateStr = persianDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    
    return persianDateStr + " - " + time;
}

这个方案不仅解决了时间显示的问题,还避免了旧API的线程安全隐患,代码可读性也更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:28:36